﻿Imports System
Imports IDServer
Imports System.Threading.Thread
Imports System.IO
Imports System.String
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient

Public Class frm_Promotion


    Implements IDServer.IDServer.IDServer

    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp

    Public mDS As DataSet  '新增表單的的資料集
    Private dsBSC As DataSet  '存放公共資料
    Private ds As New DataSet  '瀏覽表單的資料集
    Private strOriginalNum As String = "" '原始單號
    Private tempDS As New DataSet
    Private bFind As Boolean
    Private Fields As String
    Private WithEvents MainFrom As Frm_MainForm

    Public stroriginalCountry1, stroriginalProvince1, stroriginalCity1 As String
    Public stroriginalCountry, stroriginalProvince, stroriginalCity As String

    Private Captionstr As String = String.Empty
    Private CaptionStr_CHT As String = "促銷序號^Num&開始日期^StartDate&結束日期^EndDate&促銷方案^PromotionType&統一折扣^IsSame&促銷門店^Dept&折扣率^Discount&折扣金額^Reduce&購買量^PurQty&贈送量^Present&備註^Remark"
    Private CaptionStr_CHS As String = "促销序号^Num&开始日期^StartDate&结束日期^EndDate&促销方案^PromotionType&统一折扣^IsSame&促销门店^Dept&折扣率^Discount&折扣金额^Reduce&购买量^PurQty&赠送量^Present&备注^Remark"
    Private CaptionStr_EN As String = "Promotion Number^Num&Start Date^StartDate&End Date^EndDate&Promotion Program^PromotionType&Same Discount^IsSame&Store Promotions^Dept&Discount rate^Discount&Discount Amount^Reduce&Purchases Quantity^PurQty&Presented Quantity^Present&Remark^Remark"

    Private Captionstr1 As String = String.Empty
    Private CaptionStr1_CHT As String = "促銷序號^Num&序號^SN&條碼^Barcode&代碼^Code&中文貨品名^Cnname&英文貨品名^Enname&顔色^Color&規格^Spec&單位^Unit&單價^Price&折扣率(%)^Discount&折扣金額^Reduce&貨品類型^GoodsType&購買量^PurQty&贈送量^Present&備註^Remark"
    Private CaptionStr1_CHS As String = "促销序号^Num&序号^SN&条码^Barcode&代码^Code&中文货品名^Cnname&英文货品名^Enname&颜色^Color&规格^Spec&单位^Unit&单价^Price&折扣率(%)^Discount&折扣金额^Reduce&货品类型^GoodsType&购买量^PurQty&赠送量^Present&备注^Remark"
    Private CaptionStr1_EN As String = "Promotion Number^Num&Number^SN&Barcode^Barcode&Code^Code&Chinese Name^Cnname&English Name^Enname&Color^Color&Spec^Spec&Unit^Unit&Price^Price&Discount Rate(%)^Discount&Discount Amount^Reduce&Goods Type^GoodsType&Purese^PurQty&Presented Quantity^Present&Remark^Remark"


    Private mPoint As Point
    Private X, Y As Integer

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainFrom
        End Get
        Set(ByVal value As Frm_MainForm)
            MainFrom = value
        End Set
    End Property


#Region "Interface Define"


    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        Try
            If AddEnable = False Then
                MessageBox.Show(My.resources.notallowadd, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            Me.Cursor = Cursors.WaitCursor
            ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd
            Dim sql As String
            sql = "select a.Num,a.SN,a.Barcode,b.Code,b.Cnname,b.Enname,Color=c.ColorCName,Spec=e.SizeSName," & _
              "          Unit= d.ListA,a.Price,a.Qty,a.Payment,a.Tax,a.Amount,a.Remark" & _
              " from PUR_QuoteB a  left join bsc_goods b" & _
              "         on a.Barcode=b.Barcode" & _
              "        left join BSC_ColorDefine c" & _
              "        on b.Color=c.ColorCode" & _
              "        left join (select ob.ListCode,ob.ListA" & _
              "                    from BSC_OtherDefineA oa,BSC_OtherDefineB ob" & _
              "                    where oa.ItemCode ='UnitDefin'  and  oa.id=ob.ItemNo)d" & _
              "           on  b.Unit=d.ListCode" & _
              "        left join BSC_SizeDefine e" & _
              "           on  b.Spec=e.SizeCode where 1=2 "
            'mDataset = ReturnDataset(sql, "PUR_QuoteB")

            'Me.dgrd3.DataSource = mDataset.Tables("PUR_QuoteB")


            EnabledControls(True)

            Me.TabControl1.SelectedIndex = 1

            'mDataset.Tables.Clear()


            ClearText()

            With Me.dgrd3
                .Columns(0).Visible = False
                .Columns("SN").ReadOnly = True
                .Columns("Code").ReadOnly = True
                .Columns("Cnname").ReadOnly = True
                .Columns("Enname").ReadOnly = True
                .Columns("Color").ReadOnly = True
                .Columns("Spec").ReadOnly = True
                .Columns("Unit").ReadOnly = True
                .Columns("Price").ReadOnly = True

            End With


            SetButton(ButtonType.Add, False)
            Me.cmbPromotionType.Focus()
            setDgrdCol(Me.cmbPromotionType.Text)

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        Try
            Dim strCode As String
            ClearText()
            EnabledControls(False)

            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp

            If ds Is Nothing Then
                Exit Function
            End If

            IsFind = FindRecord()
            SetButton(ButtonType.Cancel, IsFind)

            If ds.Tables.Count = 0 Then
                Exit Function
            End If
            If Me.ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            IsFind = FindRecord()
            SetButton(ButtonType.Cancel, IsFind)

            If Me.dgrd1.SelectedCells.Count > 0 Then
                strCode = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value
                FillText(strCode)
            End If
            GetToolEnable()

        Catch ex As Exception
            MsgBox("ActionCancel:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete
        If DeleteEnable = False Then
            MessageBox.Show(My.Resources.NotAllowDelete, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

        Dim cnSqlServer As New SqlConnection
        cnSqlServer = GetConn()
        Dim cmdSqlServer As New SqlCommand
        Dim trnSqlServer As SqlTransaction = cnSqlServer.BeginTransaction
        Dim strNum As String
        Dim iIndex As Integer

        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            strNum = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value
            iIndex = Me.dgrd1.CurrentRow.Index
            If MsgBox("確實要刪除促銷號：" & strNum & "嗎？", MsgBoxStyle.Question Or MessageBoxButtons.YesNo, "資訊提示") = MsgBoxResult.Yes Then
                With cmdSqlServer
                    .Connection = cnSqlServer
                    .Transaction = trnSqlServer
                    .CommandType = CommandType.Text

                    '刪除記錄
                    .CommandText = "DELETE PUR_PromotionA  WHERE Num='" & strNum & "'"
                    .ExecuteNonQuery()

                End With
                trnSqlServer.Commit()


                '清空DS中相關記錄
                Dim rows() As DataRow = ds.Tables(0).Select("Num='" & strNum & "'")
                If rows.Length > 0 Then
                    For Each row As DataRow In rows
                        row.Delete()

                    Next
                End If

                rows = ds.Tables(1).Select("Num='" & strNum & "'")
                If rows.Length > 0 Then
                    For Each row As DataRow In rows
                        row.Delete()
                    Next
                End If

                ds.AcceptChanges()

                'Filter()

                IsFind = FindRecord()
                SetButton(ButtonType.Browse, IsFind)

                If IsFind = False Then
                    For I As Integer = 0 To tempDS.Tables.Count - 1
                        tempDS.Tables(I).Rows.Clear()
                    Next
                End If

                MsgBox("刪除成功！", MsgBoxStyle.OkOnly, "資訊提示")
            Else
                trnSqlServer.Rollback()


            End If
            GetToolEnable()


        Catch ex As Exception
            trnSqlServer.Rollback()
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)



        End Try
    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        Try
            If EditEnable = False Then
                MessageBox.Show(My.resources.NotAllowEidt, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            strOriginalNum = Me.txtNum.Text
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            If Me.dgrd1.SelectedCells.Count = 0 Then
                Exit Function
            End If

            If Me.TabControl1.SelectedIndex = 0 Then
                Me.TabControl1.SelectedIndex = 1
            End If

            If Me.dgrd1.SelectedCells.Count > 0 Then
                Dim Num As String = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value
                FillText(Num)
            End If

            ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
            EnabledControls(True)
            SetButton(ButtonType.Edit, False)
            Me.cmbPromotionType.Focus()
            strOriginalNum = Me.txtNum.Text
        Catch ex As Exception
            MsgBox("ActionEdit:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport
        Try
            If App.ExportEnable = False Then
                MessageBox.Show(My.Resources.NotAllowExport, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
            If Me.TabControl1.SelectedIndex = 1 Then
                Exit Function
            End If
            Me.Cursor = Cursors.WaitCursor
            If FindRecord() = False Then
                Exit Function
            Else

                Dim tb As DataTable '猁換腔桶
                'tb = CType(Me.dgrdCustomer.DataSource, DataTable)

                Dim dsTemp As DataSet = ds.Copy
                '將列名改為中文名
                For I As Integer = Me.dgrd1.Columns.Count - 1 To 0 Step -1
                    Dim strName As String = Me.dgrd1.Columns(I).Name
                    dsTemp.Tables(0).Columns(strName).Caption = Me.dgrd1.Columns(strName).HeaderText
                    '移除不需要顯示的列
                    If Me.dgrd1.Columns(I).Visible = False Then
                        dsTemp.Tables(0).Columns.Remove(strName)
                    End If
                Next


                tb = ds.Tables(1).Copy

                '將列名改為中文名
                For I As Integer = Me.dgrd2.Columns.Count - 1 To 0 Step -1
                    Dim strName As String = Me.dgrd2.Columns(I).Name
                    dsTemp.Tables(1).Columns(strName).Caption = Me.dgrd2.Columns(strName).HeaderText
                    '移除不需要顯示的列
                    If Me.dgrd2.Columns(I).Visible = False Then
                        dsTemp.Tables(1).Columns.Remove(strName)
                    End If
                Next

                '將表名改為中文名
                dsTemp.Tables(0).TableName = "促銷總覽"
                dsTemp.Tables(1).TableName = "促銷明細"


                SaveXls(dsTemp)

            End If
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst
        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            Dim row As Integer = Me.dgrd1.CurrentCell.RowIndex

            If Me.dgrd1.RowCount > 0 And Me.dgrd1.CurrentRow.Index > 0 Then
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(0).Cells(0)
                If Me.TabControl1.SelectedIndex = 1 Then
                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
                        FillText(Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value)
                    End If
                End If

            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast
        Try
            If ds Is Nothing Then
                Exit Function
            End If
            Dim row As Integer = Me.dgrd1.CurrentCell.RowIndex

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            If Me.dgrd1.RowCount > 0 Then
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(Me.dgrd1.Rows.Count - 1).Cells(0)
                If Me.TabControl1.SelectedIndex = 1 Then
                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
                        FillText(Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value)
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext
        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            Dim row As Integer = Me.dgrd1.CurrentCell.RowIndex

            If Me.dgrd1.RowCount > 0 And Me.dgrd1.CurrentRow.Index < Me.dgrd1.Rows.Count - 1 Then
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(row + 1).Cells(0)
                If Me.TabControl1.SelectedIndex = 1 Then
                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
                        FillText(Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value)
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious
        Try
            If ds Is Nothing Then
                Exit Function
            End If

            If ds.Tables.Count = 0 Then
                Exit Function
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Function
            End If

            Dim row As Integer = Me.dgrd1.CurrentCell.RowIndex

            If Me.dgrd1.RowCount > 0 And Me.dgrd1.CurrentRow.Index > 0 Then
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(row - 1).Cells(0)
                If Me.TabControl1.SelectedIndex = 1 Then
                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp Then
                        FillText(Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value)
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize
        Try

            Dim strNow, strStartDate, strEndDate As String '當前時間，促銷開始時間，促銷結束日期
            ' Dim sql, Barcode,  As String
            Dim Num As String = ""

            '促銷方案不能為空
            If Me.cmbPromotionType.Text.Length <= 0 Then
                MsgBox(My.Resources.NotNullPromotinoType, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.cmbPromotionType.Focus()
                Return False
            End If

            strNow = Now.Year.ToString + Now.Month.ToString + Now.Day.ToString
            strStartDate = Me.dtStartDate.Value.Year.ToString + "/" + Me.dtStartDate.Value.Month.ToString + "/" + Me.dtStartDate.Value.Day.ToString
            strEndDate = Me.dtEndDate.Value.Year.ToString + "/" + Me.dtEndDate.Value.Month.ToString + "/" + Me.dtEndDate.Value.Day.ToString
            strNow = Now.Year.ToString + "/" + Now.Month.ToString + "/" + Now.Day.ToString
            'strNow = Format("yyyy-MM-dd", Now)

            'strStartDate = Format("yyyy-MM-dd", Me.dtStartDate.Value)
            'strEndDate = Format("yyyy-MM-dd", Me.dtEndDate.Value)

            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                '促銷起始日期不能早於當前時間
                If Format(Me.dtStartDate.Value, "yyyy-MM-dd") < ServerDate Then
                    MsgBox(My.Resources.Promotionstartdate, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                    Me.dtStartDate.Focus()
                    Return False
                End If
                'If strStartDate < strNow Then

                'End If
            End If



            '促銷終止日期必須>=促銷起始日期
            If Me.dtStartDate.Value.CompareTo(Me.dtEndDate.Value) > 0 Then
                MsgBox(My.Resources.Promotionenddate, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.dtEndDate.Focus()
                Return False
            End If
            'If strStartDate > strEndDate Then

            'End If

            '檢查是否已經選擇促銷門店
            If Me.lstDept.CheckedItems.Count = 0 Then
                MsgBox(My.Resources.NotNullDept, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.lstDept.Focus()
                Return False

            End If

            '刪除空白行
            DelNullRecord(Me.dgrd3)

            '必須有記錄才能保存
            If Me.dgrd3.Rows.Count = 1 And Me.dgrd3.Rows(0).IsNewRow = True Then
                MsgBox(My.Resources.ZeroRecord, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Me.dgrd3.Select()
                Return False
            Else

                'Discount	Reduce GoodsType	PurQty	Present	AmountStart	AmountEnd


                '檢查資料完整性
                For I As Integer = 0 To Me.dgrd3.Rows.Count - 1

                    'Discount	Reduce	GoodsType	PurQty	Present	AmountStart	AmountEnd	Remark

                    '將非數值格式的單元格賦0
                    If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("Discount").Value) = False Then
                        Me.dgrd3.Rows(I).Cells("Discount").Value = 0
                    End If

                    If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("Reduce").Value) = False Then
                        Me.dgrd3.Rows(I).Cells("Reduce").Value = 0
                    End If

                    If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("PurQty").Value) = False Then
                        Me.dgrd3.Rows(I).Cells("PurQty").Value = 0
                    End If

                    If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("Present").Value) = False Then
                        Me.dgrd3.Rows(I).Cells("Present").Value = 0
                    End If

                    If Me.dgrd3.Rows(I).Cells("GoodsType").Value = "主貨品" Then
                        Me.dgrd3.Rows(I).Cells("Present").Value = 0
                    End If

                    If Me.dgrd3.Rows(I).Cells("GoodsType").Value = "贈送品" Then
                        Me.dgrd3.Rows(I).Cells("PurQty").Value = 0

                    End If




                    If Me.dgrd3.Rows(I).IsNewRow = False Then
                        Select Case Me.cmbPromotionType.Text
                            Case "一般折扣"

                                If Me.chkPromotion.Checked = False Then

                                    If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("Discount").Value) = False And _
                                        Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("Reduce").Value) = False Then
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("Discount")
                                        Return False

                                    End If

                                    If CDbl(Me.dgrd3.Rows(I).Cells("Discount").Value) = 0 And CDbl(Me.dgrd3.Rows(I).Cells("Reduce").Value) = 0 Then
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("Discount")
                                        Return False

                                    End If

                                    '折扣率和折扣金額只能有一個值
                                    If CDbl(Me.dgrd3.Rows(I).Cells("Discount").Value) > 0 And CDbl(Me.dgrd3.Rows(I).Cells("Reduce").Value) > 0 Then
                                        Me.dgrd3.Rows(I).Cells("Reduce").Value = 0
                                    End If

                                    '如果不使用統一折扣則將相關折扣方式明細賦值為0，將為貨品類型賦值
                                    'Discount, Reduce, GoodsType, PurQty, Present
                                    Me.dgrd3.Rows(I).Cells("GoodsType").Value = ""
                                    Me.dgrd3.Rows(I).Cells("PurQty").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Present").Value = 0

                                Else
                                    '必須選擇折扣方式  

                                    If Me.radDiscount.Checked = True And Me.nudDiscount.Value = 0 Then
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.nudDiscount.Focus()
                                        Return False
                                    End If

                                    If Me.radReduce.Checked = True And Me.nudReduce.Value = 0 Then
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.nudReduce.Focus()
                                        Return False
                                    End If

                                    '如果不使用統一折扣則將相關折扣方式明細賦值為0，將為貨品類型賦值
                                    'Discount, Reduce, GoodsType, PurQty, Present
                                    Me.dgrd3.Rows(I).Cells("Discount").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Reduce").Value = 0
                                    Me.dgrd3.Rows(I).Cells("GoodsType").Value = ""
                                    Me.dgrd3.Rows(I).Cells("PurQty").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Present").Value = 0

                                End If


                            Case "買幾送幾"

                                If Me.chkPromotion.Checked = False Then
                                    If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("PurQty").Value) = False Then
                                        Me.dgrd3.Rows(I).Cells("PurQty").Value = 0
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("PurQty")
                                        Return False
                                    End If

                                    If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("Present").Value) = False Then
                                        Me.dgrd3.Rows(I).Cells("Present").Value = 0
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("Present")
                                        Return False
                                    End If

                                    If CDbl(Me.dgrd3.Rows(I).Cells("PurQty").Value) = 0 Then
                                        MsgBox(Msg.NotNullQty, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("PurQty")
                                        Return False

                                    End If

                                    If CDbl(Me.dgrd3.Rows(I).Cells("Present").Value) = 0 Then
                                        MsgBox(Msg.NotNullQty, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("Present")
                                        Return False

                                    End If

                                    '如果不使用統一折扣則將相關折扣方式明細賦值為0，將為貨品類型賦值
                                    'Discount, Reduce, GoodsType, PurQty, Present
                                    Me.dgrd3.Rows(I).Cells("GoodsType").Value = ""
                                    Me.dgrd3.Rows(I).Cells("Discount").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Reduce").Value = 0

                                Else
                                    If Me.radBuyMany.Checked = True And Me.nudPurQty.Value = 0 Then
                                        MsgBox(Msg.NotNullQty, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.nudPurQty.Focus()
                                        Return False
                                    End If

                                    If Me.radBuyMany.Checked = True And Me.nudPresent.Value = 0 Then
                                        MsgBox(Msg.NotNullQty, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.nudPresent.Focus()
                                        Return False
                                    End If

                                    '如果不使用統一折扣則將相關折扣方式明細賦值為0，將為貨品類型賦值
                                    'Discount, Reduce, GoodsType, PurQty, Present
                                    Me.dgrd3.Rows(I).Cells("Discount").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Reduce").Value = 0
                                    Me.dgrd3.Rows(I).Cells("GoodsType").Value = ""
                                    Me.dgrd3.Rows(I).Cells("PurQty").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Present").Value = 0

                                End If


                            Case "買A送B"

                                If Me.chkPromotion.Checked = False Then

                                    If Me.dgrd3.Rows(I).Cells("GoodsType").Value = "" Then
                                        MsgBox(Msg.NotNullGoodsType, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("GoodsType")
                                        Return False
                                    End If

                                    '至少有一個促銷主貨品
                                    Dim intCount As Integer = 0
                                    intCount = CountRecode(dgrd3, "GoodsType", "主貨品")
                                    If intCount = 0 Then
                                        MsgBox(GetMsg("PUR", "NotMainGoods"), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("GoodsType")
                                        Return False
                                    End If


                                    '至少有一個贈送品

                                    intCount = CountRecode(dgrd3, "GoodsType", "贈送品")
                                    If intCount = 0 Then
                                        MsgBox(GetMsg("PUR", "NotPresentGoods"), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("GoodsType")
                                        Return False
                                    End If


                                    If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("PurQty").Value) = False Then
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("PurQty")
                                        Return False
                                    End If

                                    If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("Present").Value) = False Then
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("Present")
                                        Return False
                                    End If

                                    If Me.dgrd3.Rows(I).Cells("GoodsType").Value = "主貨品" And CDbl(Me.dgrd3.Rows(I).Cells("PurQty").Value) = 0 Then
                                        MsgBox(Msg.NotNullQty, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("PurQty")
                                        Return False

                                    End If

                                    If Me.dgrd3.Rows(I).Cells("GoodsType").Value = "贈送品" And CDbl(Me.dgrd3.Rows(I).Cells("Present").Value) = 0 Then
                                        MsgBox(Msg.NotNullQty, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("Present")
                                        Return False

                                    End If

                                    '如果不使用統一折扣則將相關折扣方式明細賦值為0，將為貨品類型賦值
                                    'Discount, Reduce, GoodsType, PurQty, Present
                                    Me.dgrd3.Rows(I).Cells("Discount").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Reduce").Value = 0


                                Else
                                    If Me.radBuyMany.Checked = False Then
                                        Me.radBuyMany.Checked = True
                                    End If
                                    If Me.nudPurQty.Value = 0 Then
                                        MsgBox(Msg.NotNullQty, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.nudPurQty.Focus()
                                        Return False
                                    End If

                                    If Me.nudPresent.Value = 0 Then
                                        MsgBox(Msg.NotNullQty, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.nudPresent.Focus()
                                        Return False
                                    End If


                                    '如果不使用統一折扣則將相關折扣方式明細賦值為0，將為貨品類型賦值
                                    'Discount, Reduce, GoodsType, PurQty, Present
                                    Me.dgrd3.Rows(I).Cells("Discount").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Reduce").Value = 0
                                    Me.dgrd3.Rows(I).Cells("PurQty").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Present").Value = 0

                                End If


                            Case "套裝優惠"

                                If Me.chkPromotion.Checked = False Then

                                    If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("Discount").Value) = False Or _
                                        Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(I).Cells("Reduce").Value) = False Then
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("Discount")
                                        Return False

                                    End If

                                    If CDbl(Me.dgrd3.Rows(I).Cells("Discount").Value) = 0 And CDbl(Me.dgrd3.Rows(I).Cells("Reduce").Value) = 0 Then
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.dgrd3.CurrentCell = Me.dgrd3.Rows(I).Cells("Discount")
                                        Return False

                                    End If

                                    If CDbl(Me.dgrd3.Rows(I).Cells("Discount").Value) > 0 And CDbl(Me.dgrd3.Rows(I).Cells("Reduce").Value) > 0 Then
                                        Me.dgrd3.Rows(I).Cells("Reduce").Value = 0

                                    End If

                                    '如果不使用統一折扣則將相關折扣方式明細賦值為0，將為貨品類型賦值
                                    'Discount, Reduce, GoodsType, PurQty, Present
                                    Me.dgrd3.Rows(I).Cells("GoodsType").Value = ""
                                    Me.dgrd3.Rows(I).Cells("PurQty").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Present").Value = 0

                                Else
                                    If Me.radDiscount.Checked = True And Me.nudDiscount.Value = 0 Then
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.nudDiscount.Focus()
                                        Return False
                                    End If

                                    If Me.radReduce.Checked = True And Me.nudReduce.Value = 0 Then
                                        MsgBox(My.Resources.NotNullDiscount, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                                        Me.nudReduce.Focus()
                                        Return False
                                    End If

                                    '如果不使用統一折扣則將相關折扣方式明細賦值為0，將為貨品類型賦值
                                    'Discount, Reduce, GoodsType, PurQty, Present
                                    Me.dgrd3.Rows(I).Cells("Discount").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Reduce").Value = 0
                                    Me.dgrd3.Rows(I).Cells("GoodsType").Value = ""
                                    Me.dgrd3.Rows(I).Cells("PurQty").Value = 0
                                    Me.dgrd3.Rows(I).Cells("Present").Value = 0

                                End If


                        End Select
                    End If

                Next



            End If

            '檢查促銷方式是否有重復
            If IsProValid(Me.cmbPromotionType.Text) = True Then
                MsgBox(GetMsg("PUR", "MSG001"), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
                Return False
            End If


            Return True
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        Try
            If ActionInitialize() = False Then Exit Function

            If BtnActionSave() = True Then
                IsFind = FindRecord()
                SetButton(ButtonType.Browse, IsFind)
                Return True
            Else
                IsFind = FindRecord()
                SetButton(ButtonType.Browse, IsFind)
                Return False
            End If
        Catch ex As Exception
            MsgBox("ActionSave:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try


    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect
        Filter()
    End Function


    ''' <summary>
    ''' 核准單據
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionChecked() As Boolean
        If CheckEnable = False Then
            MessageBox.Show("對不起，您沒有審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

    End Function

    ''' <summary>
    ''' 反核准單據
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionUnChecked() As Boolean
        If CheckEnable = False Then
            MessageBox.Show("對不起，您沒有反審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Exit Function
        End If

    End Function
#End Region

#Region "Windows Sub"
    Private Sub frm_Promotion_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try


            Me.dtDate1.Value = Now
            Me.dtDate2.Value = Now

            Me.dtStartDate.Value = Now
            Me.dtEndDate.Value = Now

            '將TabPage3移除
            Me.TabControl1.TabPages.Remove(Me.TabGiftSetup)
            ''变更语言开始语句
            If str_language.ToString.Trim.Length <= 0 Then
                str_language = ReadSystemlanguage()
            End If
            If str_language.ToString.ToString.Length <= 0 Then
                str_language = Msg.Systemdefaultlanguage
            End If
            Select Case str_language
                Case "zh-CHT"
                    str_language = "zh-CHT"
                    Captionstr = CaptionStr_CHT
                Case "zh-CHS"
                    str_language = "zh-CHS"
                    Captionstr = CaptionStr_CHS
                Case "en"
                    str_language = "en"
                    Captionstr = CaptionStr_EN
            End Select
            System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(App.str_language)
            DataBindGrid(Me.dgrd1, Captionstr)
            FormatDataGridView(Me.dgrd1)
            SetGridCaptionVisible(Me.dgrd1, Fields, "Frm_Promotion")

            With Me.dgrd1
                .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
            End With
            ''结束语句

            '綁定並格式化dgrd1、dgrd2
            'DataBindGrid(Me.dgrd1, CaptionStr)
            BindGridCaption(Me.dgrd1, BindHashTable(CaptionStr))

            With Me.dgrd1
                .ReadOnly = True
                .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing
                .SelectionMode = DataGridViewSelectionMode.CellSelect
                .MultiSelect = False
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False

            End With

            Select Case str_language
                Case "zh-CHT"
                    str_language = "zh-CHT"
                    Captionstr1 = CaptionStr1_CHT
                Case "zh-CHS"
                    str_language = "zh-CHS"
                    Captionstr1 = CaptionStr1_CHS
                Case "en"
                    str_language = "en"
                    Captionstr1 = CaptionStr1_EN
            End Select
            System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(App.str_language)
            DataBindGrid(Me.dgrd2, Captionstr)
            FormatDataGridView(Me.dgrd2)
            SetGridCaptionVisible(Me.dgrd2, Fields, "Frm_Promotion")

            'DataBindGrid(Me.dgrd2, CaptionStr1)
            BindGridCaption(Me.dgrd2, BindHashTable(CaptionStr1))
            With Me.dgrd2
                .ReadOnly = True
                .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing
                .SelectionMode = DataGridViewSelectionMode.CellSelect
                .MultiSelect = False
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
            End With


            ReBindControls()

            EnabledControls(False)


            setDgrdCol(dgrd3, CaptionStr1)
            setDgrdCol("一般折扣")

            '先移除列
            Me.dgrd3.Columns.Remove("GoodsType")

            '添加列


            Dim col As New DataGridViewComboBoxColumn
            With col
                .Name = "GoodsType"
                .HeaderText = "貨品類型"

                .Items.Add("")
                .Items.Add("主貨品")
                '.Items.Add("從貨品")
                .Items.Add("贈送品")
                .DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton

            End With

            Dim index As Integer = Me.dgrd3.Columns("PurQty").Index
            Me.dgrd3.Columns.Insert(index, col)


            With Me.dgrd3
                .Columns(0).Visible = False
                .Columns("SN").ReadOnly = True
                .Columns("Code").ReadOnly = True
                .Columns("Cnname").ReadOnly = True
                .Columns("Enname").ReadOnly = True
                .Columns("Color").ReadOnly = True
                .Columns("Spec").ReadOnly = True
                .Columns("Unit").ReadOnly = True
                .Columns("Price").ReadOnly = True

                .Columns("Barcode").Frozen = True
            End With
            Me.btnFind.Enabled = FindEnable
            ReadDgrdStyle(Me)
            ''LoadMultiLanguage()
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub
    Private Sub btnSelectAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectAll.Click
        lsvChecked(Me.lstDept, True)
    End Sub

    Private Sub dgrd3_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrd3.CellDoubleClick
        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd OrElse ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
            SelectGoodsForm()
        End If
    End Sub

    Private Sub dgrd3_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrd3.CellEnter


        'Try


        '    '1.綁定btnOpen
        '    Dim countHeight As Integer = Me.dgrd3.Top '前面單元格總的高度
        '    Dim countWidth As Integer = Me.dgrd3.Left + Me.dgrd3.RowHeadersWidth
        '    Dim intCurrentRow As Integer = Me.dgrd3.CurrentRow.Index + 1
        '    For i As Integer = 0 To Me.dgrd3.CurrentCell.RowIndex
        '        countHeight += Me.dgrd3.Rows(i).Height

        '    Next



        '    '為科目代碼列添加Bottom按鈕
        '    If Me.dgrd3.CurrentCell.ColumnIndex = 2 Then
        '        With Me.btnOpen
        '            .Visible = True
        '            .Height = Me.dgrd3.CurrentRow.Height
        '            .Left = Me.dgrd3.Left + Me.dgrd3.RowHeadersWidth _
        '              + Me.dgrd3.Columns(0).Width + Me.dgrd3.Columns(1).Width _
        '             + (Me.dgrd3.Columns(2).Width - .Width) - 100

        '            .Top = countHeight + (Me.dgrd3.ColumnHeadersHeight - .Height)

        '        End With
        '        Me.btnOpen.Visible = True

        '    Else
        '        Me.btnOpen.Visible = False
        '    End If

        '    ''計算寬度
        '    'For I As Integer = 0 To 11
        '    '    If Me.dgrd3.Columns(I).Visible = True Then
        '    '        countWidth += Me.dgrd3.Columns(I).Width
        '    '    End If
        '    'Next


        '    ''為科目代碼列添加ComboBox按鈕
        '    'If Me.dgrd3.CurrentCell.ColumnIndex = 12 Then
        '    '    With Me.cmbGoodsType
        '    '        .Visible = True
        '    '        .Height = Me.dgrd3.CurrentRow.Height
        '    '        .Left = Me.dgrd3.CurrentCell.ContentBounds.Left


        '    '        .Top = countHeight + (Me.dgrd3.ColumnHeadersHeight - .Height)

        '    '        .Left = 453
        '    '        .Top = 19

        '    '    End With
        '    '    Me.cmbGoodsType.Visible = True

        '    'Else
        '    '    Me.cmbGoodsType.Visible = False
        '    'End If



        '    UpdateSN()

        'Catch ex As Exception
        '    MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        'End Try

    End Sub

    Private Sub btnClearAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearAll.Click
        lsvChecked(Me.lstDept, False)
    End Sub

    ''' <summary>
    ''' 重新綁定控件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        ReBindControls()
    End Sub

    Private Sub cmbPromotionType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbPromotionType.SelectedIndexChanged
        Try
            If Me.cmbPromotionType.SelectedValue Is Nothing Then
                Exit Sub
            End If

            setDgrdCol(Me.cmbPromotionType.Text)

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub
    ''' <summary>
    ''' 是否使用同一折扣方式
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub chkPromotion_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkPromotion.CheckedChanged
        Try

            Me.GBxDiscountMode.Enabled = Me.chkPromotion.Checked
            Me.dgrd3.Columns("Discount").ReadOnly = Me.chkPromotion.Checked
            Me.dgrd3.Columns("Reduce").ReadOnly = Me.chkPromotion.Checked
            Me.dgrd3.Columns("GoodsType").ReadOnly = Me.chkPromotion.Checked And (Me.cmbPromotionType.Text <> "買A送B")
            Me.dgrd3.Columns("PurQty").ReadOnly = Me.chkPromotion.Checked
            Me.dgrd3.Columns("Present").ReadOnly = Me.chkPromotion.Checked

            If Me.chkPromotion.Checked = False Then
                Me.nudPurQty.Value = 0
                Me.nudPresent.Value = 0
            End If


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub TabControl1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TabControl1.KeyDown
        If Me.TabControl1.SelectedIndex = 1 Then

            Try
                If e.KeyCode = Keys.F2 Then

                    If Me.TabControl1.SelectedIndex = 1 Then
                        If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                            If Not ((Me.dgrd3.Focused = False And Me.dgrd3.Rows(Me.dgrd3.CurrentRow.Index).Cells("Barcode").Selected = True) _
                                 Or Me.dgrd3.Focused = True) Then
                                Exit Sub
                            End If
                            '    If Me.dgrd3.CurrentCell.ColumnIndex = 2 And Me.dgrd3.Rows(Me.dgrd3.CurrentRow.Index).Cells("Barcode").ReadOnly = False Then
                            '        Dim Frm_SelectGoods As New Frm_SelectGoods
                            '        Dim ICurrentRowIndex As Integer

                            '        If Me.dgrd3.CurrentRow Is Nothing Then
                            '            ICurrentRowIndex = 0
                            '        Else
                            '            ICurrentRowIndex = Me.dgrd3.CurrentRow.Index

                            '        End If

                            '        '原始行號
                            '        Dim IorgRowIndex As Integer = ICurrentRowIndex

                            '        '= DataGridView3.CurrentRow.Index
                            '        Frm_SelectGoods.StartPosition = FormStartPosition.CenterScreen
                            '        If Me.cmbPromotionType.Text = "總金額階梯優惠" Then
                            '            PubMultiSelect = False
                            '        Else
                            '            PubMultiSelect = True
                            '        End If

                            '        Frm_SelectGoods.ShowDialog()

                            '        If PubGoodsDataSet.Tables.Count = 0 Then
                            '            Exit Sub
                            '        End If

                            '        '1.將選擇的資料複製到臨時表
                            '        Dim tb As New DataTable
                            '        tb = PubGoodsDataSet.Tables(0)

                            '        If tb.Rows.Count > 0 Then
                            '            Dim intRows = tb.Rows.Count - 1
                            '            Dim Obj1, Obj2, Obj3, Obj4, Obj5, Obj6, Obj7, Obj8 As Object
                            '            For I As Integer = 0 To tb.Rows.Count - 1
                            '                Obj1 = tb.Rows(I).Item("Barcode")
                            '                Obj2 = tb.Rows(I).Item("Code")
                            '                Obj3 = tb.Rows(I).Item("Cnname")
                            '                Obj4 = tb.Rows(I).Item("Enname")
                            '                Obj5 = tb.Rows(I).Item("Color")
                            '                Obj6 = tb.Rows(I).Item("Spec")
                            '                Obj7 = tb.Rows(I).Item("Unit")
                            '                Obj8 = tb.Rows(I).Item("Price")

                            '                '2.檢查是否有重復記錄
                            '                Dim key As String
                            '                Dim intCount As Object

                            '                key = tb.Rows(I).Item("Barcode")
                            '                intCount = CountRecode(dgrd3, "Barcode", key)

                            '                '如果沒有重復記錄
                            '                If intCount = 0 Then
                            '                    '如果是第1條記錄
                            '                    If I = 0 Then
                            '                        Me.dgrd3.Rows(ICurrentRowIndex).Cells("Barcode").Value = tb.Rows(I).Item("Barcode")
                            '                        Me.dgrd3.Rows(ICurrentRowIndex).Cells("Code").Value = tb.Rows(I).Item("Code")
                            '                        Me.dgrd3.Rows(ICurrentRowIndex).Cells("Cnname").Value = tb.Rows(I).Item("Cnname")
                            '                        Me.dgrd3.Rows(ICurrentRowIndex).Cells("Enname").Value = tb.Rows(I).Item("Enname")
                            '                        Me.dgrd3.Rows(ICurrentRowIndex).Cells("Color").Value = tb.Rows(I).Item("Color")
                            '                        Me.dgrd3.Rows(ICurrentRowIndex).Cells("Spec").Value = tb.Rows(I).Item("Spec")
                            '                        Me.dgrd3.Rows(ICurrentRowIndex).Cells("Unit").Value = tb.Rows(I).Item("Unit")
                            '                        Me.dgrd3.Rows(ICurrentRowIndex).Cells("Price").Value = tb.Rows(I).Item("Price")
                            '                    Else

                            '                        '判斷當前行是否是最後一行
                            '                        If Me.dgrd3.CurrentRow.Index = Me.dgrd3.Rows.Count - 1 Then
                            '                            Me.dgrd3.Rows.Add("", "", Obj1, Obj2, Obj3, Obj4, Obj5, Obj6, _
                            '                                                                              Obj7, Obj8, "", "", "", "", "", "")

                            '                        Else
                            '                            Me.dgrd3.Rows.Insert(ICurrentRowIndex, "", "", Obj1, Obj2, Obj3, Obj4, Obj5, Obj6, _
                            '                                                                              Obj7, Obj8, "", "", "", "", "", "")
                            '                        End If

                            '                    End If

                            '                End If
                            '                ICurrentRowIndex += 1
                            '            Next


                            '            PubGoodsDataSet.Tables(0).Rows.Clear()

                            '            Dim rowTemp As DataGridViewRow

                            '            '刪除空白行
                            '            For i As Integer = Me.dgrd3.Rows.Count - 1 To 0 Step -1
                            '                If IsDBNull(Me.dgrd3.Rows(i).Cells("Code").Value) Then
                            '                    Me.dgrd3.Rows.RemoveAt(i)

                            '                End If

                            '                '判斷是否為新建行
                            '                If Me.dgrd3.Rows(i).IsNewRow = True And Me.dgrd3.Rows(i).Cells("code").Value <> "" Then
                            '                    rowTemp = Me.dgrd3.Rows(i)
                            '                    Obj1 = Me.dgrd3.Rows(i).Cells("Barcode").Value
                            '                    Obj2 = Me.dgrd3.Rows(i).Cells("Code").Value
                            '                    Obj3 = Me.dgrd3.Rows(i).Cells("Cnname").Value
                            '                    Obj4 = Me.dgrd3.Rows(i).Cells("Enname").Value
                            '                    Obj5 = Me.dgrd3.Rows(i).Cells("Color").Value
                            '                    Obj6 = Me.dgrd3.Rows(i).Cells("Spec").Value
                            '                    Obj7 = Me.dgrd3.Rows(i).Cells("Unit").Value
                            '                    Obj8 = Me.dgrd3.Rows(i).Cells("Price").Value
                            '                    For K As Integer = 0 To Me.dgrd3.Columns.Count - 1

                            '                        Me.dgrd3.Rows(i).Cells(K).Value = ""
                            '                    Next
                            '                    Me.dgrd3.Rows.Insert(IorgRowIndex, "", "", Obj1, Obj2, Obj3, Obj4, Obj5, Obj6, _
                            '                                                                            Obj7, Obj8, "", "", "", "", "", "")
                            '                End If
                            '            Next



                            '            Me.dgrd3.Refresh()

                            '            UpdateSN()
                            '        End If

                            '    End If
                            SelectGoodsForm()
                        End If
                    End If

                End If
            Catch ex As Exception
                MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            End Try
        End If
    End Sub


    Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click


        Try
            Dim Frm_SelectGoods As New Frm_SelectGoods
            Dim ICurrentRowIndex As Integer

            If Me.dgrd3.CurrentRow Is Nothing Then
                ICurrentRowIndex = 0
            Else
                ICurrentRowIndex = Me.dgrd3.CurrentRow.Index

            End If

            '= DataGridView3.CurrentRow.Index
            Frm_SelectGoods.StartPosition = FormStartPosition.CenterScreen
            Frm_SelectGoods.ShowDialog()

            If PubGoodsDataSet.Tables.Count = 0 Then
                Exit Sub
            End If

            Dim tb As New DataTable
            tb = PubGoodsDataSet.Tables(0)

            If tb.Rows.Count > 0 Then
                For I As Integer = 0 To tb.Rows.Count - 1
                    Me.dgrd3.Rows.Add()

                    Me.dgrd3.Rows(ICurrentRowIndex).Cells("Barcode").Value = tb.Rows(I).Item("Barcode")
                    Me.dgrd3.Rows(ICurrentRowIndex).Cells("Code").Value = tb.Rows(I).Item("Code")
                    Me.dgrd3.Rows(ICurrentRowIndex).Cells("Cnname").Value = tb.Rows(I).Item("Cnname")
                    Me.dgrd3.Rows(ICurrentRowIndex).Cells("Enname").Value = tb.Rows(I).Item("Enname")
                    Me.dgrd3.Rows(ICurrentRowIndex).Cells("Color").Value = tb.Rows(I).Item("Color")
                    Me.dgrd3.Rows(ICurrentRowIndex).Cells("Spec").Value = tb.Rows(I).Item("Spec")
                    Me.dgrd3.Rows(ICurrentRowIndex).Cells("Unit").Value = tb.Rows(I).Item("Unit")
                    Me.dgrd3.Rows(ICurrentRowIndex).Cells("Price").Value = tb.Rows(I).Item("Price")


                    ICurrentRowIndex += 1

                Next


                PubGoodsDataSet.Tables(0).Rows.Clear()

                UpdateSN()
                '刪除空白行
                For i As Integer = Me.dgrd3.Rows.Count - 1 To 0 Step -1
                    If IsDBNull(Me.dgrd3.Rows(i).Cells("Code").Value) Then
                        Me.dgrd3.Rows.RemoveAt(i)

                    End If
                Next

                UpdateSN()
            End If

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)


        End Try

    End Sub


    Private Sub dgrd3_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrd3.CellEndEdit
        Try

            If Me.dgrd3.Rows(e.RowIndex).IsNewRow = False Then
                If IsNumeric(Me.dgrd3.Rows(e.RowIndex).Cells("Discount").Value) = False Or IsMatch(Me.dgrd3.Rows(e.RowIndex).Cells("Discount").Value, 2) = False Then
                    Me.dgrd3.Rows(e.RowIndex).Cells("Discount").Value = 0
                End If

                If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(e.RowIndex).Cells("Discount").Value) = True Then
                    If CDbl(Me.dgrd3.Rows(e.RowIndex).Cells("Discount").Value) >= 100 Then
                        Me.dgrd3.Rows(e.RowIndex).Cells("Discount").Value = 0
                    End If
                End If


                If IsNumeric(Me.dgrd3.Rows(e.RowIndex).Cells("Reduce").Value) = False Or IsMatch(Me.dgrd3.Rows(e.RowIndex).Cells("Reduce").Value, 2) = False Then
                    Me.dgrd3.Rows(e.RowIndex).Cells("Reduce").Value = 0
                End If

                If Microsoft.VisualBasic.IsNumeric(Me.dgrd3.Rows(e.RowIndex).Cells("Reduce").Value) = True Then
                    If CDbl(Me.dgrd3.Rows(e.RowIndex).Cells("Reduce").Value) >= CDbl(Me.dgrd3.Rows(e.RowIndex).Cells("Price").Value) Then
                        Me.dgrd3.Rows(e.RowIndex).Cells("Reduce").Value = 0
                    End If
                End If

                If IsNumeric(Me.dgrd3.Rows(e.RowIndex).Cells("PurQty").Value) = False Or IsMatch(Me.dgrd3.Rows(e.RowIndex).Cells("PurQty").Value, 2) = False Then
                    Me.dgrd3.Rows(e.RowIndex).Cells("PurQty").Value = 0
                End If

                If IsNumeric(Me.dgrd3.Rows(e.RowIndex).Cells("Present").Value) = False Or IsMatch(Me.dgrd3.Rows(e.RowIndex).Cells("Present").Value, 2) = False Then
                    Me.dgrd3.Rows(e.RowIndex).Cells("Present").Value = 0
                End If


            End If
            UpdateSN()


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub dgrd3_CellLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrd3.CellLeave, dgrd3.CellValidated
        Try
            If e.ColumnIndex = 2 Then

                If Me.dgrd3.Rows(e.RowIndex).Cells("Barcode").Value = "" Then
                    Exit Sub
                Else
                    Dim strBarcode As String = Me.dgrd3.Rows(e.RowIndex).Cells("Barcode").Value
                    Dim Sql As String
                    Sql = "SELECT top 1    barcode = Substring(a.barcode,2,Len(Rtrim(a.barcode)) - 2),"
                    Sql = Sql & "                 a.code,"
                    Sql = Sql & "                 a.cnname,"
                    Sql = Sql & "                 a.enname,"
                    Sql = Sql & "                 color = e.colorcname,"
                    Sql = Sql & "                 spec = j.sizesname,"
                    Sql = Sql & "                 unit = b.lista,"
                    Sql = Sql & "                 a.price,"
                    Sql = Sql & "                 goodstype = f.ffullname"
                    Sql = Sql & " FROM   dbo.bsc_goods a"
                    Sql = Sql & "        LEFT JOIN (SELECT c.itemcode,"
                    Sql = Sql & "                          d.listcode,"
                    Sql = Sql & "                          d.lista"
                    Sql = Sql & "                   FROM   bsc_otherdefinea c,"
                    Sql = Sql & "                          bsc_otherdefineb d"
                    Sql = Sql & "                   WHERE  c.itemcode = 'UnitDefin'"
                    Sql = Sql & "                          AND c.id = d.itemno) b"
                    Sql = Sql & "          ON a.unit = b.listcode"
                    Sql = Sql & "        LEFT JOIN bsc_colordefine e"
                    Sql = Sql & "          ON a.color = e.colorcode"
                    Sql = Sql & "        LEFT JOIN bsc_goodstype f"
                    Sql = Sql & "          ON a.goodstype = f.id"
                    Sql = Sql & "        LEFT JOIN bsc_storehouse i"
                    Sql = Sql & "          ON a.storehouse = i.fcode"
                    Sql = Sql & "        LEFT JOIN bsc_sizedefine j"
                    Sql = Sql & "          ON a.spec = j.sizecode"
                    Sql = Sql & "  where barcode='*" & strBarcode & "*' and a.Status=1  "
                    tempDS = ReturnDataset(Sql)
                    '單價^Price&折扣率(%)^Discount&折扣金額^Reduce&貨品類型^GoodsType&購買量^PurQty&贈送量^Present&備註^Remark"
                    If tempDS.Tables(0).Rows.Count = 0 Then
                        Me.dgrd3.Rows(e.RowIndex).Cells("Barcode").Value = ""
                        Me.dgrd3.Rows(e.RowIndex).Cells("Code").Value = ""
                        Me.dgrd3.Rows(e.RowIndex).Cells("Cnname").Value = ""
                        Me.dgrd3.Rows(e.RowIndex).Cells("Enname").Value = ""
                        Me.dgrd3.Rows(e.RowIndex).Cells("Color").Value = ""
                        Me.dgrd3.Rows(e.RowIndex).Cells("Spec").Value = ""
                        Me.dgrd3.Rows(e.RowIndex).Cells("Unit").Value = ""
                        Me.dgrd3.Rows(e.RowIndex).Cells("Price").Value = 0


                        Exit Sub
                    Else
                        '2.檢查是否有重復記錄
                        Dim key As String
                        Dim intCount As Object

                        key = tempDS.Tables(0).Rows(0).Item("Barcode")
                        intCount = CountRecode(dgrd3, "Barcode", key)

                        If intCount = 1 Then
                            Me.dgrd3.Rows(e.RowIndex).Cells("Barcode").Value = tempDS.Tables(0).Rows(0).Item("Barcode")
                            Me.dgrd3.Rows(e.RowIndex).Cells("Code").Value = tempDS.Tables(0).Rows(0).Item("Code")
                            Me.dgrd3.Rows(e.RowIndex).Cells("Cnname").Value = tempDS.Tables(0).Rows(0).Item("Cnname")
                            Me.dgrd3.Rows(e.RowIndex).Cells("Enname").Value = tempDS.Tables(0).Rows(0).Item("Enname")
                            Me.dgrd3.Rows(e.RowIndex).Cells("Color").Value = tempDS.Tables(0).Rows(0).Item("Color")
                            Me.dgrd3.Rows(e.RowIndex).Cells("Spec").Value = tempDS.Tables(0).Rows(0).Item("Spec")
                            Me.dgrd3.Rows(e.RowIndex).Cells("Unit").Value = tempDS.Tables(0).Rows(0).Item("Unit")
                            Me.dgrd3.Rows(e.RowIndex).Cells("Price").Value = tempDS.Tables(0).Rows(0).Item("Price")
                        Else
                            Me.dgrd3.Rows(e.RowIndex).Cells("Barcode").Value = ""

                        End If

                    End If

                End If

            End If

            'PurQty&贈送量^Present



            'If IsNumeric(Me.dgrd3.Rows(e.RowIndex).Cells("Price").Value) = False Or IsMatch(Me.dgrd3.Rows(e.RowIndex).Cells("Price").Value, 2) = False Then
            '    Me.dgrd3.Rows(e.RowIndex).Cells("Price").Value = 0
            'End If

            'If IsNumeric(Me.dgrd3.Rows(e.RowIndex).Cells("qty").Value) = False Or IsMatch(Me.dgrd3.Rows(e.RowIndex).Cells("qty").Value, 2) = False Then
            '    Me.dgrd3.Rows(e.RowIndex).Cells("qty").Value = 1
            'End If

            UpdateSN()


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind.Click
        MainFrom.ToolStripFind_Click(Nothing, Nothing)
    End Sub

    Private Sub dgrd1_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgrd1.CurrentCellChanged
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim mytb As New DataTable

            Dim Num As String
            If Me.dgrd1.DataSource Is Nothing Then
                Exit Sub
            End If

            If Me.dgrd1.SelectedCells.Count <= 0 Then
                Exit Sub

            End If

            If Me.dgrd1.CurrentCell Is Nothing Then
                Exit Sub
            End If

            Num = Me.dgrd1.CurrentRow.Cells(0).Value
            If Num Is Nothing Then
                Exit Sub
            Else
                ds.Tables("t_Detail").Select("Num='" & Num & "'")
                'Dim tempDS As New DataSet
                Dim tb As New DataTable
                tb = ds.Tables("t_Detail").Copy
                tb.Rows.Clear()

                If tempDS Is Nothing Then
                    Exit Sub
                End If

                If tempDS.Tables.Count > 0 Then
                    tempDS.Tables.Clear()
                End If

                tempDS.Tables.Add(tb)

                For Each row As DataRow In ds.Tables("t_Detail").Select("Num='" & Num & "'")
                    Dim mRow As DataRow
                    mRow = tb.NewRow()
                    For Each col As DataColumn In tb.Columns
                        mRow(col) = row.Item(col.ColumnName)
                    Next
                    tb.Rows.Add(mRow)
                    tempDS.AcceptChanges()

                Next

                Me.dgrd2.DataSource = tempDS.Tables(0)

                'setDgrdRowNumber(Me.dgrd1)


            End If

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try



    End Sub

    Private Sub dgrd1_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgrd1.DoubleClick
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Exit Sub
            End If
            If ds.Tables.Count = 0 Then
                Exit Sub
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Sub
            End If

            If Me.TabControl1.SelectedIndex = 0 Then
                'Me.TabControl1.SelectedIndex = 1
                If IsDBNull(Me.dgrd1.Rows(0).Cells(0).Value) Then
                    Exit Sub
                Else
                    Dim Num As String = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells("Num").Value

                    FillText(Num)

                End If
                Me.TabControl1.SelectedIndex = 1
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub radDiscount_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radDiscount.CheckedChanged, _
                           radReduce.CheckedChanged, radBuyMany.CheckedChanged
        Try
            Me.nudDiscount.Enabled = Me.radDiscount.Checked
            Me.nudReduce.Enabled = Me.radReduce.Checked
            Me.GroupBox2.Enabled = Me.radBuyMany.Checked
            Me.nudDiscount.Value = IIf(Me.radDiscount.Checked = False, 0, Me.nudDiscount.Value)
            Me.nudReduce.Value = IIf(Me.radReduce.Checked = False, 0, Me.nudReduce.Value)
            Me.nudPurQty.Value = IIf(Me.radBuyMany.Checked = False, 0, Me.nudPurQty.Value)
            Me.nudPresent.Value = IIf(Me.radBuyMany.Checked = False, 0, Me.nudPresent.Value)

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        Try
            Me.Cursor = Cursors.WaitCursor
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Exit Sub
            End If
            If ds Is Nothing Then
                Exit Sub
            End If

            If ds.Tables.Count = 0 Then
                Exit Sub
            End If

            If ds.Tables(0).Rows.Count = 0 Then
                Exit Sub
            End If

            If Me.TabControl1.SelectedIndex = 1 Then
                If Me.dgrd1.SelectedCells.Count > 0 Then
                    Dim Num As String = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0).Value
                    FillText(Num)
                End If
            End If

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub txtNum1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtNum1.KeyDown, txtNum2.KeyDown, txtBarcode2.KeyDown _
          , txtBarcode1.KeyDown, txtBarcode2.KeyDown, dtDate1.KeyDown, dtDate2.KeyDown, cmbPromotionType1.KeyDown, cmbPromotionType2.KeyDown, _
           cmbDept1.KeyDown, cmbDept2.KeyDown, btnFind.KeyDown, txtNum.KeyDown, cmbPromotionType.KeyDown, dtStartDate.KeyDown, dtEndDate.KeyDown _
           , chkPromotion.KeyDown, radDiscount.KeyDown, nudDiscount.KeyDown, radReduce.KeyDown, nudReduce.KeyDown, radBuyMany.KeyDown, _
            nudPresent.KeyDown, nudPurQty.KeyDown, txtRemark.KeyDown, btnSelectAll.KeyDown, btnClearAll.KeyDown, btnRefresh.KeyDown
        Try
            If e.KeyCode = Keys.Shift Then
                e.Handled = True
                If e.KeyCode = Keys.Enter Then
                    SendKeys.Send("+{TAB}")
                    SendKeys.Send("{F4}")
                End If
            Else
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        SendKeys.Send("{TAB}")
                        SendKeys.Send("{F4}")
                End Select
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub dgrd1_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles dgrd1.RowPostPaint
        Try
            Dim rectangle As New Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, Me.dgrd1.RowHeadersWidth - 4, e.RowBounds.Height)
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), Me.dgrd1.RowHeadersDefaultCellStyle.Font, _
               rectangle, dgrd1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.Right)

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub mnuSaveStyle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSaveStyle.Click
        SaveDgrdStyle(Me)
    End Sub

#End Region

#Region "Function Define"
    ''' <summary>
    '''  初始化ds
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Initialize()
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim Table(1) As String
            Dim sql(1) As String
            sql(0) = "SELECT Distinct  a.Num, a.StartDate, a.EndDate, a.PromotionType, IsSame=(CASE IsSame WHEN 1 THEN '是' ELSE '否' END)," & _
             " Dept=dbo.GetDept(Dept), a.Discount, a.Reduce,a.PurQty,a.Present, a.Remark   FROM PUR_PromotionA a left join PUR_PromotionB b " & _
             "   ON a.Num=b.Num " & _
             "   WHERE 1=2 "

            sql(1) = "select a.Num,a.SN,Barcode=substring(a.barcode,2,len(rtrim(a.barcode))-2),b.Code,b.Cnname," & _
                      "   b.Enname,Color=c.ColorCName,Spec=e.SizeSName,  Unit= d.ListA,b.Price," & _
                      "   a.Discount, a.Reduce, a.GoodsType, a.PurQty, a.Present,a.Remark " & _
                      "   from PUR_PromotionB a  left join bsc_goods b " & _
                      "   on a.Barcode=b.Barcode " & _
                      "  left join BSC_ColorDefine c " & _
                      " on b.Color=c.ColorCode  " & _
                      " left join (select ob.ListCode,ob.ListA  " & _
                      " from BSC_OtherDefineA oa,BSC_OtherDefineB ob  " & _
                      " where oa.ItemCode ='UnitDefin'  and  oa.id=ob.ItemNo)d " & _
                      "  on  b.Unit=d.ListCode " & _
                     " left join BSC_SizeDefine e  " & _
                     "  on  b.Spec=e.SizeCode where 1=2 "

            Table(0) = "t_Master"
            Table(1) = "t_Detail"

            ds = GetDataSet(sql, Table)

            Me.dgrd1.DataSource = ds.Tables("t_Master")
            Me.dgrd2.DataSource = ds.Tables("t_Detail")

            If ds.Tables("t_Master").Rows.Count > 0 Then
                setDgrdRowNumber(Me.dgrd1)
            End If

            IsFind = FindRecord()

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default

        End Try

    End Function
    ''' <summary>
    ''' 獲取公共資料
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub GetPublic()
        Try
            'Dim strSQL As String
            'strSQL = " select ListCode,ListA from dbo.BSC_OtherDefineB  " & _
            '         " where ItemNo=(Select ID from BSC_OtherDefineA where ItemCode='PromotionType') ;" & _
            '         "select '' ListCode,'' ListA union " & _
            '         " select ListCode,ListA from dbo.BSC_OtherDefineB  " & _
            '         " where ItemNo=(Select ID from BSC_OtherDefineA where ItemCode='PromotionType') ;" & _
            '         "select '' ListCode,'' ListA union " & _
            '         " select ListCode,ListA from dbo.BSC_OtherDefineB  " & _
            '         " where ItemNo=(Select ID from BSC_OtherDefineA where ItemCode='PromotionType') ;"

            'dsBSC = ReturnDataset(strSQL)
            'dsBSC.Tables(0).TableName = "PromotionType"
            'dsBSC.Tables(1).TableName = "PromotionType1"
            'dsBSC.Tables(2).TableName = "PromotionType2"

            Dim Table(5) As String
            Dim sql(5) As String

            '促銷方案
            Table(0) = "PromotionType"
            sql(0) = " select ListCode,ListA from dbo.BSC_OtherDefineB  " & _
                     " where ItemNo=(Select ID from BSC_OtherDefineA where ItemCode='PromotionType') ;"

            '促銷方案
            Table(1) = "PromotionType1"
            sql(1) = "select '' ListCode,'' ListA union " & _
                     " select ListCode,ListA from dbo.BSC_OtherDefineB  " & _
                     " where ItemNo=(Select ID from BSC_OtherDefineA where ItemCode='PromotionType') ;"

            '促銷方案
            Table(2) = "PromotionType2"
            sql(2) = "select '' ListCode,'' ListA union " & _
                     " select ListCode,ListA from dbo.BSC_OtherDefineB  " & _
                     " where ItemNo=(Select ID from BSC_OtherDefineA where ItemCode='PromotionType') ;"


            '門店
            Table(3) = "BSC_Dept"
            sql(3) = "select fCode,fCName from dbo.BSC_Dept "


            '門店
            Table(4) = "BSC_Dept1"
            sql(4) = "select '' fCode,'' fCName union  " & _
                     "select fCode,fCName from dbo.BSC_Dept order by fCode "

            '門店
            Table(5) = "BSC_Dept2"
            sql(5) = "select '' fCode,'' fCName union  " & _
                     "select fCode,fCName from dbo.BSC_Dept order by fCode "


            dsBSC = GetDataSet(sql, Table)


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 保存資料
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function BtnActionSave() As Boolean

        Dim cnSqlServer As New SqlConnection
        cnSqlServer = GetConn()
        Dim cmdSqlServer As New SqlCommand
        Dim trnSqlServer As SqlTransaction = cnSqlServer.BeginTransaction

        Try
            Dim sql As String = ""
            'Dim M_Ds As New DataSet

            '促銷序號
            Dim Num As String
            Num = GetValue("select dbo.getMaxNum('Promotion')")

            Dim intNewNum As Integer '新號碼
            intNewNum = CInt(GetValue("select Number from Number where BillType='Promotion'")) + 1

            '促銷方案
            Dim PromotionType As String

            PromotionType = Me.cmbPromotionType.Text

            '起始日期，終止日期
            Dim StartDate, EndDate As String
            StartDate = Me.dtStartDate.Value.Year.ToString + "/" + Me.dtStartDate.Value.Month.ToString + "/" + Me.dtStartDate.Value.Day.ToString
            EndDate = Me.dtEndDate.Value.Year.ToString + "/" + Me.dtEndDate.Value.Month.ToString + "/" + Me.dtEndDate.Value.Day.ToString

            '是否使用統一折扣
            Dim IsSame As Integer = IIf(Me.chkPromotion.Checked = True, 1, 0)
            Dim strIsSame As String = IIf(Me.chkPromotion.Checked = True, "是", "否")

            '統一折扣方式
            Dim Discount, Reduce, PurQty, Present As Double

            Discount = Me.nudDiscount.Value
            Reduce = Me.nudReduce.Value
            PurQty = Me.nudPurQty.Value
            Present = Me.nudPresent.Value

            '備註
            Dim Remark As String = Me.txtRemark.Text.Replace("'", "")

            '部門
            Dim Dept, strDept As String
            Dept = ""
            strDept = ""
            For I As Integer = 0 To Me.lstDept.Items.Count - 1
                If Me.lstDept.Items(I).Checked = True Then
                    Dept += Me.lstDept.Items(I).Tag + ","
                    strDept += Me.lstDept.Items(I).Text + ","
                End If
            Next

            If Dept.Length > 0 Then
                '去掉最後一個，
                Dept = Dept.Substring(0, Dept.Length - 1)
                strDept = strDept.Substring(0, strDept.Length - 1)
            End If


            If ActionInitialize() = False Then Exit Function

            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                'Num, StartDate, EndDate, PromotionType, IsSame, Dept, Discount, Reduce, PurQty, Present, Remark
                sql = "Insert Into PUR_PromotionA(Num, StartDate, EndDate, PromotionType, IsSame, Dept, Discount, Reduce, PurQty, Present," & _
                        " Remark, BillstatusID, BulidDate, LastUpdateDate," & _
                         " BulidComputer, LastUpdateComputer, BulidBy, LastUpdateBy)  values('" & _
                          Num & "','" & StartDate & "','" & EndDate & "','" & PromotionType & "'," & IsSame & ",'" & _
                          Dept & "'," & Discount & "," & Reduce & "," & PurQty & "," & Present & ",'" & _
                          Remark & "','A'," & _
                          "convert(varchar(19),getdate(),120)," & "convert(varchar(19),getdate(),120)," & _
                          "host_name()," & "host_name(),'" & PubUserName & "','" & PubUserName & "');"

                AddtoDataSet(Num, StartDate, EndDate, PromotionType, strIsSame, strDept, Discount, Reduce, PurQty, Present, Remark)



            Else

                sql = "Update PUR_PromotionA Set " & _
                      "StartDate='" & StartDate & _
                      "',EndDate='" & EndDate & _
                      "',PromotionType='" & PromotionType & _
                      "',IsSame=" & IsSame & _
                      ",Dept='" & Dept & _
                      "',Discount=" & Discount & _
                      ",Reduce=" & Reduce & _
                      ",PurQty=" & PurQty & _
                      ",Present=" & Present & _
                      ",Remark='" & Remark & _
                      "',BillstatusID='A" & _
                      "',LastUpdateDate=convert(varchar(19),getdate(),120)" & _
                      ",LastUpdateComputer=host_name()" & _
                      ",LastUpdateBy='" & PubUserName & _
                       "' where Num='" & strOriginalNum & "'"


                EditToDataSet(strOriginalNum, StartDate, EndDate, PromotionType, strIsSame, strDept, Discount, Reduce, PurQty, Present, Remark)

            End If

            With cmdSqlServer
                .Connection = cnSqlServer
                .Transaction = trnSqlServer
                .CommandType = CommandType.Text

                '添加或修改PUR_PromotionA
                .CommandText = sql
                .ExecuteNonQuery()

                '添加或修改PUR_PromotionB
                If Me.dgrd3.Rows.Count > 0 Then

                    '如果是修改狀態
                    If Me.txtNum.TextLength > 0 Then
                        .CommandText = "DELETE PUR_PromotionB WHERE Num='" & strOriginalNum & "'"
                        .ExecuteNonQuery()
                    End If

                    '循環插入記錄到PUR_PromotionB
                    For I As Integer = 0 To Me.dgrd3.Rows.Count - 1
                        If Me.dgrd3.Rows(I).IsNewRow = False Then
                            'Num, SN, Barcode, Discount, Reduce, GoodsType, PurQty, Present, Remark
                            Dim SN As String = Me.dgrd3.Rows(I).Cells("SN").Value
                            Dim Barcode As String = "*" + Me.dgrd3.Rows(I).Cells("Barcode").Value.ToString.Trim + "*"
                            Dim GoodsType As String = Me.dgrd3.Rows(I).Cells("GoodsType").Value & ""
                            Discount = Me.dgrd3.Rows(I).Cells("Discount").Value
                            Reduce = Me.dgrd3.Rows(I).Cells("Reduce").Value
                            PurQty = Me.dgrd3.Rows(I).Cells("PurQty").Value
                            Present = Me.dgrd3.Rows(I).Cells("Present").Value
                            If IsDBNull(Me.dgrd3.Rows(I).Cells("Remark").Value) Then
                                Remark = ""
                            Else
                                Remark = Me.dgrd3.Rows(I).Cells("Remark").Value & ""
                            End If

                            If Me.txtNum.TextLength > 0 Then
                                .CommandText = "insert into PUR_PromotionB VALUES ('" & strOriginalNum & "','" & SN & "','" & _
                                                                          Barcode & "'," & Discount & "," & Reduce & ",'" & GoodsType & "'," & _
                                                                          PurQty & "," & Present & ",'" & Remark & "')"
                            Else
                                .CommandText = "insert into PUR_PromotionB VALUES ('" & Num & "','" & SN & "','" & _
                                                                                          Barcode & "'," & Discount & "," & Reduce & ",'" & GoodsType & "'," & _
                                                                                          PurQty & "," & Present & ",'" & Remark & "')"
                            End If

                            .ExecuteNonQuery()

                        End If
                    Next


                    '更新Number
                    If Me.txtNum.Text = "" Then
                        .CommandText = "update Number set Number=" & intNewNum & " where BillType='Promotion'"
                        .ExecuteNonQuery()
                    End If



                End If


            End With

            trnSqlServer.Commit()

            '增加或修改ds.Tables("t_Detail")
            If Me.txtNum.TextLength > 0 Then
                If ds Is Nothing Then Exit Function
                Dim Rows() As DataRow = ds.Tables(1).Select("Num='" & strOriginalNum & "'")
                If Rows.Length > 0 Then
                    For Each row As DataRow In Rows
                        row.Delete()
                    Next
                End If
            End If
            ds.AcceptChanges()


            If ds Is Nothing Then
                Initialize()
            End If

            For I As Integer = 0 To Me.dgrd3.Rows.Count - 1
                If Me.dgrd3.Rows(I).IsNewRow = False Then

                    Dim SN As String = Me.dgrd3.Rows(I).Cells("SN").Value
                    Dim Barcode As String = Me.dgrd3.Rows(I).Cells("Barcode").Value.ToString.Trim
                    Dim Code As String = Me.dgrd3.Rows(I).Cells("Code").Value.ToString.Trim & ""
                    Dim Cnname As String = Me.dgrd3.Rows(I).Cells("Cnname").Value.ToString.Trim & ""
                    Dim Enname As String = Me.dgrd3.Rows(I).Cells("Enname").Value.ToString.Trim & ""
                    Dim Color As String = Me.dgrd3.Rows(I).Cells("Color").Value.ToString.Trim & ""
                    Dim Spec As String = Me.dgrd3.Rows(I).Cells("Spec").Value.ToString.Trim & ""
                    Dim Unit As String = Me.dgrd3.Rows(I).Cells("Unit").Value.ToString.Trim & ""
                    Dim Price As Double = Me.dgrd3.Rows(I).Cells("Price").Value

                    Dim GoodsType As String = Me.dgrd3.Rows(I).Cells("GoodsType").Value & ""
                    Discount = Me.dgrd3.Rows(I).Cells("Discount").Value
                    Reduce = Me.dgrd3.Rows(I).Cells("Reduce").Value
                    PurQty = Me.dgrd3.Rows(I).Cells("PurQty").Value
                    Present = Me.dgrd3.Rows(I).Cells("Present").Value
                    If IsDBNull(Me.dgrd3.Rows(I).Cells("Remark").Value) Then
                        Remark = ""
                    Else
                        Remark = Me.dgrd3.Rows(I).Cells("Remark").Value & ""
                    End If

                    Dim mRow As DataRow
                    mRow = ds.Tables("t_Detail").NewRow
                    If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                        mRow("Num") = Num
                    Else
                        mRow("Num") = strOriginalNum
                    End If

                    mRow("SN") = SN
                    mRow("Barcode") = Barcode
                    mRow("Code") = Code
                    mRow("Cnname") = Cnname
                    mRow("Enname") = Enname
                    mRow("Color") = Color
                    mRow("Spec") = Spec
                    mRow("Unit") = Unit
                    mRow("Price") = Price
                    mRow("Discount") = Discount
                    mRow("Reduce") = Reduce
                    mRow("GoodsType") = GoodsType
                    mRow("PurQty") = PurQty
                    mRow("Present") = Present
                    mRow("Remark") = Remark
                    ds.Tables("t_Detail").Rows.Add(mRow)

                End If

                ds.Tables("t_Detail").AcceptChanges()
            Next

            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                Me.txtNum.Text = Num

            End If


            MsgBox(IIf(ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd, My.Resources.AddSuccess, My.Resources.EditSuccess), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
            'Me.Panel2.Enabled = False

            If Me.dgrd1.SelectedCells.Count > 0 Then
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(1)
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(Me.dgrd1.CurrentRow.Index).Cells(0)

            End If
            EnabledControls(False)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            GetToolEnable()
            Return True
        Catch ex As Exception
            trnSqlServer.Rollback()
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
            Return False

        Finally
            'Filter()
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
        End Try
    End Function

    Private Sub AddtoDataSet(ByVal Num As String, ByVal StartDate As String, ByVal EndDate As String, _
                             ByVal PromotionType As String, ByVal IsSame As String, ByVal Dept As String, _
                             ByVal Discount As Double, ByVal Reduce As Double, ByVal PurQty As Double, _
                             ByVal Present As Double, ByVal Remark As String)

        Try
            If ds Is Nothing Then
                Initialize()
            End If

            If ds.Tables.Count = 0 Then
                Initialize()
            End If

            Dim mRow As DataRow
            mRow = ds.Tables(0).NewRow
            mRow("Num") = Num
            mRow("StartDate") = StartDate
            mRow("EndDate") = EndDate
            mRow("PromotionType") = PromotionType
            mRow("IsSame") = IsSame
            mRow("Dept") = Dept
            mRow("Discount") = Discount
            mRow("Reduce") = Reduce
            mRow("PurQty") = PurQty
            mRow("Present") = Present
            mRow("Remark") = Remark

            ds.Tables(0).Rows.Add(mRow)
            ds.Tables(0).AcceptChanges()
        Catch ex As Exception
            MsgBox("AddtoDataSet:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub EditToDataSet(ByVal Num As String, ByVal StartDate As String, ByVal EndDate As String, _
                             ByVal PromotionType As String, ByVal IsSame As String, ByVal Dept As String, _
                             ByVal Discount As Double, ByVal Reduce As Double, ByVal PurQty As Double, _
                             ByVal Present As Double, ByVal Remark As String)

        Try
            If ds Is Nothing Then Exit Sub
            Dim Rows() As DataRow = ds.Tables(0).Select("Num='" & strOriginalNum & "'")
            If Rows.Length > 0 Then
                For Each mRow As DataRow In Rows
                    mRow("Num") = Num
                    mRow("StartDate") = StartDate
                    mRow("EndDate") = EndDate
                    mRow("PromotionType") = PromotionType
                    mRow("IsSame") = IsSame
                    mRow("Dept") = Dept
                    mRow("Discount") = Discount
                    mRow("Reduce") = Reduce
                    mRow("PurQty") = PurQty
                    mRow("Present") = Present
                    mRow("Remark") = Remark

                Next
                ds.AcceptChanges()
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 設置控件的Enable屬性
    ''' </summary>
    ''' <param name="B"></param>
    ''' <remarks></remarks>
    Private Sub EnabledControls(ByVal B As Boolean)
        Me.Panel4.Enabled = B
        Me.dgrd3.ReadOnly = Not B
        Me.GroupBox3.Enabled = B

    End Sub

    ''' <summary>
    ''' 設置按鈕狀態
    ''' </summary>
    ''' <param name="type"></param>
    ''' <remarks></remarks>
    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try
            Select Case type
                Case ButtonType.Add
                    With MainFrom
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Browse
                    With MainFrom
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = IsFind
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Cancel
                    With MainFrom
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = IsFind
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = IsFind
                        .ToolStripLast.Enabled = IsFind
                        .ToolStripNext.Enabled = IsFind
                        .ToolStripPrivous.Enabled = IsFind
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

                Case ButtonType.Edit
                    With MainFrom
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = IsFind
                        .ToolStripImport.Enabled = True
                        .ToolStripPrint.Enabled = IsFind
                        .ToolStripFilter.Enabled = True

                    End With

            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub


    ''' <summary>
    ''' 判斷是否有記錄
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function FindRecord() As Boolean

        If ds Is Nothing Then
            Return False
            Exit Function
        End If

        If Me.dgrd1.RowCount = 0 Then
            Return False
        Else
            Return True

        End If




    End Function


    ''' <summary>
    ''' 設置DataGridView的列標題
    ''' </summary>
    ''' <param name="dgrd"></param>
    ''' <param name="caption"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function setDgrdCol(ByVal dgrd As DataGridView, ByVal caption As String)
        Try
            Dim Str() As String = caption.Split("&")
            '如果DataGridView沒有列，則添加列
            If dgrd.Columns.Count = 0 Then
                For i As Integer = 0 To Str.Length - 1
                    Dim strName, strHeaderText As String
                    strName = Str(i).Split("^")(1)
                    strHeaderText = Str(i).Split("^")(0)
                    dgrd.Columns.Add(strName, strHeaderText)

                Next
            Else '否則修改列標題
                For i As Integer = 0 To Str.Length - 1
                    Dim strName, strHeaderText As String
                    strName = Str(i).Split("^")(0)
                    strHeaderText = Str(i).Split("^")(1)
                    dgrd.Columns(strName).HeaderText = strHeaderText

                Next

            End If


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Private Sub UpdateSN()
        Try
            'If Me.dgrd3.Rows.Count = 1 And Me.dgrd3.Rows(0).IsNewRow Then
            '    Exit Sub
            'End If

            For I As Integer = 0 To Me.dgrd3.Rows.Count - 1
                With Me.dgrd3
                    .Item("SN", I).Value = Microsoft.VisualBasic.StrDup(3 - Len((I + 1).ToString), "0") + (I + 1).ToString
                End With
            Next


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' ClearText()
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ClearText()
        Try
            Me.txtNum.Text = ""
            Me.cmbPromotionType.SelectedIndex = 0
            Me.dtStartDate.Value = Now
            Me.dtEndDate.Value = Now
            Me.txtRemark.Text = ""

            If Me.dgrd3.Rows.Count > 1 Then
                Me.dgrd3.Rows.Clear()
            End If

            If mDS Is Nothing = False Then
                If mDS.Tables.Count > 0 Then
                    mDS.Tables(0).Rows.Clear()
                End If
            End If

            Me.radDiscount.Checked = False
            Me.radReduce.Checked = False
            Me.radBuyMany.Checked = False
            Me.nudDiscount.Value = 0
            Me.nudPresent.Value = 0
            Me.nudPurQty.Value = 0
            Me.nudReduce.Value = 0

            Me.chkPromotion.Checked = False
            lsvChecked(Me.lstDept, False)

            UpdateSN()

            'Me.dgrd3.CurrentCell = Me.dgrd3.Rows(0).Cells(2)


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 重新綁定控制項的資料源
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ReBindControls()
        Try
            GetPublic()

            '綁定數據
            With Me.cmbPromotionType1
                .DataSource = dsBSC.Tables("PromotionType1")
                .ValueMember = ("ListCode")
                .DisplayMember = ("ListA")
            End With

            With Me.cmbPromotionType2
                .DataSource = dsBSC.Tables("PromotionType2")
                .ValueMember = ("ListCode")
                .DisplayMember = ("ListA")
            End With

            With Me.cmbPromotionType
                .DataSource = dsBSC.Tables("PromotionType")
                .ValueMember = ("ListCode")
                .DisplayMember = ("ListA")
            End With


            With Me.cmbDept1
                .DataSource = dsBSC.Tables("BSC_Dept1")
                .ValueMember = ("fCode")
                .DisplayMember = ("fCName")
            End With

            With Me.cmbDept2
                .DataSource = dsBSC.Tables("BSC_Dept2")
                .ValueMember = ("fCode")
                .DisplayMember = ("fCName")
            End With


            ''填充ListView1

            With Me.lstDept
                .Columns.Clear()

                .CheckBoxes = True
                .View = View.Details
                .Columns.Add("門店", 180, HorizontalAlignment.Center)

                .Items.Clear()
                For I As Integer = 0 To dsBSC.Tables("BSC_Dept").Rows.Count - 1
                    Dim item As New ListViewItem
                    With item
                        .Tag = dsBSC.Tables("BSC_Dept").Rows(I).Item("fCode").ToString
                        .Text = dsBSC.Tables("BSC_Dept").Rows(I).Item("fCName").ToString

                    End With
                    .Items.Add(item)
                Next

            End With



        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try


    End Sub

    ''' <summary>
    ''' 根據折扣類型確定dgrd3中列的Visible
    ''' </summary>
    ''' <param name="type"></param>
    ''' <remarks></remarks>
    Private Sub SetDgrdCol(ByVal type As String)
        Try
            Select Case type
                Case "一般折扣"
                    If Me.radDiscount.Checked = False And Me.radReduce.Checked = False Then
                        Me.radDiscount.Checked = True
                    End If

                    Me.chkPromotion.Enabled = True

                    With Me.dgrd3
                        .Columns("Discount").Visible = True
                        .Columns("Reduce").Visible = True
                        .Columns("GoodsType").Visible = False
                        .Columns("PurQty").Visible = False
                        .Columns("Present").Visible = False

                    End With


                    Me.radDiscount.Enabled = True
                    Me.radReduce.Enabled = True
                    Me.radBuyMany.Enabled = False
                    Me.radBuyMany.Checked = False
                    Me.GroupBox2.Enabled = False

                    'For I As Integer = 0 To Me.dgrd3.Columns.Count - 1
                    '    Console.WriteLine("ColumnName:{0},Visible:{1}", Me.dgrd3.Columns(I).Name, Me.dgrd3.Columns(I).Visible)

                    'Next

                Case "買幾送幾"
                    Me.chkPromotion.Enabled = True

                    Me.dgrd3.Columns("Barcode").ReadOnly = False
                    With Me.dgrd3
                        .Columns("Discount").Visible = False
                        .Columns("Reduce").Visible = False
                        .Columns("GoodsType").Visible = False
                        .Columns("PurQty").Visible = True
                        .Columns("Present").Visible = True


                    End With

                    Me.radDiscount.Enabled = False
                    Me.radReduce.Enabled = False
                    Me.radBuyMany.Enabled = True
                    Me.radBuyMany.Checked = True
                    Me.GroupBox2.Enabled = True

                Case "買A送B"
                    'Me.chkPromotion.Enabled = False

                    With Me.dgrd3
                        .Columns("Discount").Visible = False
                        .Columns("Reduce").Visible = False
                        .Columns("GoodsType").Visible = True
                        .Columns("PurQty").Visible = True
                        .Columns("Present").Visible = True

                    End With

                    Me.radDiscount.Enabled = False
                    Me.radReduce.Enabled = False
                    Me.radBuyMany.Enabled = True
                    Me.radBuyMany.Checked = True
                    Me.GroupBox2.Enabled = True

                Case "套裝優惠"

                    Me.chkPromotion.Enabled = True

                    If Me.radDiscount.Checked = False And Me.radReduce.Checked = False Then
                        Me.radDiscount.Checked = True
                    End If

                    With Me.dgrd3
                        .Columns("Discount").Visible = True
                        .Columns("Reduce").Visible = True
                        .Columns("GoodsType").Visible = False
                        .Columns("PurQty").Visible = False
                        .Columns("Present").Visible = False

                    End With

                    Me.radDiscount.Enabled = True
                    Me.radReduce.Enabled = True
                    Me.radBuyMany.Enabled = False
                    Me.radBuyMany.Checked = False
                    Me.GroupBox2.Enabled = False

            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 查找DataGridView中某欄位的相同記錄數
    ''' </summary>
    ''' <param name="dgrd">需要統計的DataGridview</param>
    ''' <param name="colName">要統計的列名</param>
    ''' <param name="Key">要統計的值</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CountRecode(ByVal dgrd As DataGridView, ByVal colName As String, ByVal Key As String) As Integer
        Try
            Dim intCount As Integer = 0
            If dgrd.Rows.Count = 0 Then
                Return intCount
                Exit Function
            End If


            For I As Integer = 0 To dgrd.Rows.Count - 1
                If dgrd.Rows(I).Cells(colName).Value = Key Then
                    intCount += 1
                End If
            Next

            Return intCount

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    ''' <summary>
    ''' 刪除DataGridView的空行
    ''' </summary>
    ''' <param name="dgrd">要刪除空白行的DataGridView</param>
    ''' <remarks></remarks>
    Private Sub DelNullRecord(ByVal dgrd As DataGridView)
        Try

            '刪除空白行
            For i As Integer = dgrd.Rows.Count - 1 To 0 Step -1
                If dgrd.Rows(i).Cells("Code").Value = "" And dgrd.Rows(i).IsNewRow = False Then
                    dgrd.Rows.RemoveAt(i)

                End If
            Next

            dgrd.Refresh()
            UpdateSN()
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 過濾符合條件的記錄
    ''' </summary>
    ''' <remarks></remarks>
    Sub Filter()
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Exit Sub
            End If

            Me.Cursor = Cursors.WaitCursor
            Dim dt1, dt2 As String
            dt1 = Me.dtDate1.Value.Year.ToString + "/" + Me.dtDate1.Value.Month.ToString + "/" + Me.dtDate1.Value.Day.ToString
            dt2 = Me.dtDate2.Value.Year.ToString + "/" + Me.dtDate2.Value.Month.ToString + "/" + Me.dtDate2.Value.Day.ToString

            Dim Table(1) As String
            Dim sql(1) As String
            sql(0) = "SELECT Distinct  a.Num, a.StartDate, a.EndDate, a.PromotionType, IsSame=(CASE IsSame WHEN 1 THEN '是' ELSE '否' END)," & _
             " Dept=dbo.GetDept(Dept), a.Discount, a.Reduce,a.PurQty,a.Present, a.Remark   FROM PUR_PromotionA a left join PUR_PromotionB b " & _
             "   ON a.Num=b.Num " & _
             "   WHERE 1=1 "
            sql(0) += " and a.StartDate >= '" & dt1 & "'  and a.EndDate<='" & dt2 & "' "

            '促銷序號
            If Me.txtNum1.TextLength > 0 Then
                sql(0) += " and a.Num>='" & Me.txtNum1.Text & "' "
            End If

            If Me.txtNum2.TextLength > 0 Then
                sql(0) += " and a.Num<='" & Me.txtNum2.Text & "' "
            End If

            '條碼
            If Me.txtBarcode1.TextLength > 0 Then
                sql(0) += " and b.Barcode>='*" & Me.txtBarcode1.Text & "*' "
            End If

            If Me.txtBarcode2.TextLength > 0 Then
                sql(0) += " and b.Barcode<='*" & Me.txtBarcode1.Text & "*' "
            End If

            '促銷方案
            If Me.cmbPromotionType1.Text.Length > 0 Then
                sql(0) += " and a.PromotionType>='" & Me.cmbPromotionType1.Text & "' "
            End If

            If Me.cmbPromotionType2.Text.Length > 0 Then
                sql(0) += " and a.PromotionType<='" & Me.cmbPromotionType2.Text & "' "
            End If

            '促銷門店
            If Me.cmbDept1.Text.Length > 0 Then
                sql(0) += " and charindex('" & Me.cmbDept1.Text & "',dbo.GetDept(a.Dept))>0 "
            End If

            If Me.cmbDept2.Text.Length > 0 Then
                sql(0) += " and charindex('" & Me.cmbDept2.Text & "',dbo.GetDept(a.Dept))>0 "
            End If

            sql(0) += " Order by a.Num"

            sql(1) = "select Num into #temp  from ( " & sql(0).Replace(" Order by a.Num", "") & ") z;"
            sql(1) += "select a.Num,a.SN,Barcode=substring(a.barcode,2,len(rtrim(a.barcode))-2),b.Code,b.Cnname," & _
                      "   b.Enname,Color=c.ColorCName,Spec=e.SizeSName,  Unit= d.ListA,b.Price," & _
                      "   a.Discount, a.Reduce, a.GoodsType, a.PurQty, a.Present,a.Remark " & _
                      "   from PUR_PromotionB a  left join bsc_goods b " & _
                      "   on a.Barcode=b.Barcode " & _
                      "  left join BSC_ColorDefine c " & _
                      " on b.Color=c.ColorCode  " & _
                      " left join (select ob.ListCode,ob.ListA  " & _
                      " from BSC_OtherDefineA oa,BSC_OtherDefineB ob  " & _
                      " where oa.ItemCode ='UnitDefin'  and  oa.id=ob.ItemNo)d " & _
                      "  on  b.Unit=d.ListCode " & _
                     " left join BSC_SizeDefine e  " & _
                     "  on  b.Spec=e.SizeCode where a.Num in (select num from #temp) "

            Table(0) = "t_Master"
            Table(1) = "t_Detail"

            ds = GetDataSet(sql, Table)

            'ds.Relations.Add("R_Master_Detail", ds.Tables("t_Master").Columns("Num"), ds.Tables("t_Detail").Columns("Num"), True)
            Me.dgrd1.DataSource = ds.Tables("t_Master")
            'Me.dgrd2.DataSource = ds.Tables("t_Detail")
            bFind = ds.Tables(0).Rows.Count > 0
            If ds.Tables("t_Master").Rows.Count > 0 Then
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(0).Cells(2)
                Me.dgrd1.CurrentCell = Me.dgrd1.Rows(0).Cells(0)
            Else
                Me.dgrd2.DataSource = ds.Tables("t_Detail")
                MsgBox(Msg.NotFindRecord, MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)

            End If

            IsFind = FindRecord()

            SetButton(ButtonType.Browse, IsFind)
            GetToolEnable()

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)

        Finally
            Me.Cursor = Cursors.Default
        End Try


    End Sub

    '從DataGridView選定記錄後填充Text
    Private Sub FillText(ByVal Num As String)
        Try
            ClearText()

            Dim mRow() As DataRow = ds.Tables(0).Select("Num='" & Num & "'")
            If mRow Is Nothing Then Exit Sub
            For Each Row As DataRow In mRow
                Me.txtNum.Text = Row("Num") & ""
                Me.cmbPromotionType.Text = Row("PromotionType").ToString
                Me.dtStartDate.Value = Row("StartDate") & ""
                Me.dtEndDate.Value = Row("EndDate") & ""
                Me.txtRemark.Text = Row("Remark") & ""
                If Row("IsSame") = "是" Then
                    Me.chkPromotion.Checked = True
                    If IsDBNull(Row("Discount")) = False Then
                        If Row("Discount") > 0 Then
                            Me.radDiscount.Checked = True
                            Me.nudDiscount.Value = Row("Discount")
                        End If

                    End If

                    If IsDBNull(Row("Reduce")) = False Then
                        If Row("Reduce") > 0 Then
                            Me.radReduce.Checked = True
                            Me.nudReduce.Value = Row("Reduce")
                        End If

                    End If

                    If IsDBNull(Row("PurQty")) = False Then
                        If Row("PurQty") > 0 Then
                            Me.radDiscount.Checked = True
                            Me.nudPurQty.Value = Row("PurQty")
                        End If

                    End If

                    If IsDBNull(Row("Present")) = False Then
                        If Row("Present") > 0 Then
                            Me.radDiscount.Checked = True
                            Me.nudPresent.Value = Row("Present")
                        End If

                    End If

                Else
                    Me.chkPromotion.Checked = False
                End If

                '填充部門
                If IsDBNull(Row("Present")) = False Then
                    If Len(Row("Dept")) > 0 Then
                        Dim strDept As String = Row("Dept")
                        Dim Dept As String
                        Dim str() As String = strDept.Split(",")
                        For I As Integer = 0 To str.Length - 1
                            Dept = str(I)

                            For J As Integer = 0 To Me.lstDept.Items.Count - 1
                                If Me.lstDept.Items(J).Text = Dept Then
                                    Me.lstDept.Items(J).Checked = True
                                End If
                            Next
                        Next

                    End If
                End If




            Next

            If Me.dgrd2.Rows.Count > 0 Then
                For I As Integer = 0 To Me.dgrd2.Rows.Count - 1
                    Me.dgrd3.Rows.Insert(I, 1)
                    For J As Integer = 0 To Me.dgrd2.Columns.Count - 1
                        Me.dgrd3.Rows(I).Cells(J).Value = Me.dgrd2.Rows(I).Cells(J).Value

                    Next
                Next
            End If
            setDgrdCol(Me.cmbPromotionType.Text)
            UpdateSN()


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 確認貨品的促銷是否有效
    ''' </summary>
    ''' <param name="Type">促銷類型</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function IsProValid(ByVal Type As String) As Boolean
        Try

            Dim strNow, strStartDate, strEndDate As String '當前時間，促銷開始時間，促銷結束日期
            Dim sql, Barcode, Dept As String
            Dim Num As String = Me.txtNum.Text

            strStartDate = Me.dtStartDate.Value.Year.ToString + "/" + Me.dtStartDate.Value.Month.ToString + "/" + Me.dtStartDate.Value.Day.ToString
            strEndDate = Me.dtEndDate.Value.Year.ToString + "/" + Me.dtEndDate.Value.Month.ToString + "/" + Me.dtEndDate.Value.Day.ToString
            strNow = Now.Year.ToString + "/" + Now.Month.ToString + "/" + Now.Day.ToString

            Select Case Type
                Case "一般折扣"
                    For I As Integer = 0 To Me.dgrd3.Rows.Count - 1
                        If Me.dgrd3.Rows(I).IsNewRow = False Then
                            '判?折扣是否重復
                            For K As Integer = 0 To Me.lstDept.Items.Count - 1
                                If Me.lstDept.Items(K).Checked = True Then
                                    Barcode = "*" & Me.dgrd3.Rows(I).Cells("Barcode").Value.ToString.Trim & "*"
                                    Dept = Me.lstDept.Items(K).Tag
                                    sql = "select count(Num)  From (SELECT Distinct  a.Num" & _
                                          " FROM PUR_PromotionA a left join PUR_PromotionB b " & _
                                          "   ON a.Num=b.Num WHERE b.Barcode='" & Barcode & "'  and a.PromotionType='" & _
                                          Type & "' and ((StartDate between '" & strStartDate & "' and '" & _
                                          strEndDate & "') OR (EndDate between '" & strStartDate & _
                                          "' and '" & strEndDate & "')) and CharIndex('" & Dept & _
                                          "',dept)>0  and a.Num<>'" & Num & "'  ) c"
                                    If GetValue(sql) > 0 Then
                                        Return True
                                        Exit Function
                                    End If
                                End If
                            Next
                        End If
                    Next
                Case "買幾送幾"
                    For I As Integer = 0 To Me.dgrd3.Rows.Count - 1
                        If Me.dgrd3.Rows(I).IsNewRow = False Then
                            '判?折扣是否重復
                            For K As Integer = 0 To Me.lstDept.Items.Count - 1
                                If Me.lstDept.Items(K).Checked = True Then
                                    Barcode = "*" & Me.dgrd3.Rows(I).Cells("Barcode").Value.ToString.Trim & "*"
                                    Dept = Me.lstDept.Items(K).Tag
                                    sql = "select count(Num)  From (SELECT Distinct  a.Num" & _
                                          " FROM PUR_PromotionA a left join PUR_PromotionB b " & _
                                          "   ON a.Num=b.Num WHERE b.Barcode='" & Barcode & "'  and a.PromotionType='" & _
                                          Type & "' and ((StartDate between '" & strStartDate & "' and '" & _
                                          strEndDate & "') OR (EndDate between '" & strStartDate & _
                                          "' and '" & strEndDate & "')) and CharIndex('" & Dept & _
                                          "',dept)>0  and a.Num<>'" & Num & "'  ) c"
                                    If GetValue(sql) > 0 Then
                                        Return True
                                        Exit Function
                                    End If
                                End If
                            Next
                        End If
                    Next

                Case "買A送B"

                    '判?折扣是否重復
                    For K As Integer = 0 To Me.lstDept.Items.Count - 1

                        If Me.lstDept.Items(K).Checked = True Then
                            sql = "create table #t1( [Barcode] [nvarchar](50) COLLATE Chinese_Taiwan_Stroke_CI_AS);"
                            Dept = Me.lstDept.Items(K).Tag
                            For I As Integer = 0 To Me.dgrd3.Rows.Count - 1
                                If Me.dgrd3.Rows(I).IsNewRow = False Then
                                    Barcode = "*" & Me.dgrd3.Rows(I).Cells("Barcode").Value.ToString.Trim & "*"
                                    sql += "INSERT INTO #T1 VALUES ('" & Barcode & "');"
                                End If
                            Next

                            sql += "select distinct a.Num,b.Barcode INTO #T2  from PUR_PromotionA a ," & _
                                          " PUR_PromotionB b ,#T1 c where a.PromotionType='買A送B' " & _
                                          " and ((StartDate between '" & strStartDate & "' and '" & _
                                          strEndDate & "') OR (EndDate between '" & strStartDate & _
                                          "' and '" & strEndDate & "')) and CharIndex('" & Dept & _
                                          "',dept)>0  and a.Num<>'" & Num & "'  and  a.Num=B.Num " & _
                                          " and b.Barcode=c.Barcode;"
                            sql += "select count(*) FROM (SELECT Num,COUNT(Num) as QTY FROM #T2 GROUP BY Num " & _
                                   "HAVING COUNT(Num)=(SELECT COUNT(*) FROM #T1)) a"

                            If GetValue(sql) > 0 Then
                                Return True
                                Exit Function
                            End If
                        End If
                    Next

                Case "套裝優惠"

                    '判?折扣是否重復
                    For K As Integer = 0 To Me.lstDept.Items.Count - 1

                        If Me.lstDept.Items(K).Checked = True Then
                            sql = "create table #t1( [Barcode] [nvarchar](50) COLLATE Chinese_Taiwan_Stroke_CI_AS);"
                            Dept = Me.lstDept.Items(K).Tag
                            For I As Integer = 0 To Me.dgrd3.Rows.Count - 1
                                If Me.dgrd3.Rows(I).IsNewRow = False Then
                                    Barcode = "*" & Me.dgrd3.Rows(I).Cells("Barcode").Value.ToString.Trim & "*"
                                    sql += "INSERT INTO #T1 VALUES ('" & Barcode & "');"
                                End If
                            Next

                            sql += "select distinct a.Num,b.Barcode INTO #T2  from PUR_PromotionA a ," & _
                                          " PUR_PromotionB b ,#T1 c where a.PromotionType='套裝優惠' " & _
                                          " and ((StartDate between '" & strStartDate & "' and '" & _
                                          strEndDate & "') OR (EndDate between '" & strStartDate & _
                                          "' and '" & strEndDate & "')) and CharIndex('" & Dept & _
                                          "',dept)>0  and a.Num<>'" & Num & "'  and  a.Num=B.Num " & _
                                          " and b.Barcode=c.Barcode;"
                            sql += "select count(*) FROM (SELECT Num,COUNT(Num) as QTY FROM #T2 GROUP BY Num " & _
                                   "HAVING COUNT(Num)=(SELECT COUNT(*) FROM #T1)) a"

                            If GetValue(sql) > 0 Then
                                Return True
                                Exit Function
                            End If
                        End If
                    Next



            End Select

            Return False

        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Function

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub GetToolEnable()
        Try
            With MainFrom
                .ToolStripAdd.Enabled = AddEnable
                .ToolStripEdit.Enabled = EditEnable And bFind
                .ToolStripDelete.Enabled = DeleteEnable And bFind
                .ToolStripPrint.Enabled = PrintEnable
                .ToolStripImport.Enabled = ImportEnable
                .ToolStripExport.Enabled = ExportEnable
                .ToolStripFind.Enabled = FindEnable
                .ToolStripCheck.Enabled = CheckEnable
                .ToolStripUnCheck.Enabled = UncheckEnable
                .ToolStripComplete.Enabled = CompleteEnable
                .AddToolStripMenuItem.Enabled = .ToolStripAdd.Enabled
                .Edit1ToolStripMenuItem.Enabled = .ToolStripEdit.Enabled
                .DelToolStripMenuItem.Enabled = .ToolStripDelete.Enabled
                .SaveToolStripMenuItem.Enabled = .ToolStripSave.Enabled
                .CancelToolStripMenuItem.Enabled = .ToolStripCancel.Enabled
                .PrintToolStripMenuItem.Enabled = .ToolStripPrint.Enabled
                .ExportToolStripMenuItem.Enabled = .ToolStripImport.Enabled
                .ImportToolStripMenuItem.Enabled = .ToolStripExport.Enabled
                .FilterToolStripMenuItem.Enabled = .ToolStripFilter.Enabled
            End With

        Catch ex As Exception
            MsgBox("GetToolEnable:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub


    Private Sub SelectGoodsForm()

        If Me.dgrd3.CurrentRow Is Nothing Then Exit Sub

        If Me.dgrd3.CurrentCell.ColumnIndex = 2 AndAlso Me.dgrd3.Rows(Me.dgrd3.CurrentRow.Index).Cells("Barcode").ReadOnly = False Then

            Dim Frm_SelectGoods As New Frm_SelectGoods
            Dim ICurrentRowIndex As Integer

            If Me.dgrd3.CurrentRow Is Nothing Then
                ICurrentRowIndex = 0
            Else
                ICurrentRowIndex = Me.dgrd3.CurrentRow.Index

            End If

            '原始行號
            Dim IorgRowIndex As Integer = ICurrentRowIndex

            '= DataGridView3.CurrentRow.Index
            Frm_SelectGoods.StartPosition = FormStartPosition.CenterScreen
            If Me.cmbPromotionType.Text = "總金額階梯優惠" Then
                PubMultiSelect = False
            Else
                PubMultiSelect = True
            End If

            Frm_SelectGoods.ShowDialog()

            If PubGoodsDataSet.Tables.Count = 0 Then
                Exit Sub
            End If

            '1.將選擇的資料複製到臨時表
            Dim tb As New DataTable
            tb = PubGoodsDataSet.Tables(0)

            If tb.Rows.Count > 0 Then
                Dim intRows = tb.Rows.Count - 1
                Dim Obj1, Obj2, Obj3, Obj4, Obj5, Obj6, Obj7, Obj8 As Object
                For I As Integer = 0 To tb.Rows.Count - 1
                    Obj1 = tb.Rows(I).Item("Barcode")
                    Obj2 = tb.Rows(I).Item("Code")
                    Obj3 = tb.Rows(I).Item("Cnname")
                    Obj4 = tb.Rows(I).Item("Enname")
                    Obj5 = tb.Rows(I).Item("Color")
                    Obj6 = tb.Rows(I).Item("Spec")
                    Obj7 = tb.Rows(I).Item("Unit")
                    Obj8 = tb.Rows(I).Item("Price")

                    '2.檢查是否有重復記錄
                    Dim key As String
                    Dim intCount As Object

                    key = tb.Rows(I).Item("Barcode")
                    intCount = CountRecode(dgrd3, "Barcode", key)

                    '如果沒有重復記錄
                    If intCount = 0 Then
                        '如果是第1條記錄
                        If I = 0 Then
                            Me.dgrd3.Rows(ICurrentRowIndex).Cells("Barcode").Value = tb.Rows(I).Item("Barcode")
                            Me.dgrd3.Rows(ICurrentRowIndex).Cells("Code").Value = tb.Rows(I).Item("Code")
                            Me.dgrd3.Rows(ICurrentRowIndex).Cells("Cnname").Value = tb.Rows(I).Item("Cnname")
                            Me.dgrd3.Rows(ICurrentRowIndex).Cells("Enname").Value = tb.Rows(I).Item("Enname")
                            Me.dgrd3.Rows(ICurrentRowIndex).Cells("Color").Value = tb.Rows(I).Item("Color")
                            Me.dgrd3.Rows(ICurrentRowIndex).Cells("Spec").Value = tb.Rows(I).Item("Spec")
                            Me.dgrd3.Rows(ICurrentRowIndex).Cells("Unit").Value = tb.Rows(I).Item("Unit")
                            Me.dgrd3.Rows(ICurrentRowIndex).Cells("Price").Value = tb.Rows(I).Item("Price")
                        Else

                            '判斷當前行是否是最後一行
                            If Me.dgrd3.CurrentRow.Index = Me.dgrd3.Rows.Count - 1 Then
                                Me.dgrd3.Rows.Add("", "", Obj1, Obj2, Obj3, Obj4, Obj5, Obj6, _
                                                                                  Obj7, Obj8, "", "", "", "", "", "")

                            Else
                                Me.dgrd3.Rows.Insert(ICurrentRowIndex, "", "", Obj1, Obj2, Obj3, Obj4, Obj5, Obj6, _
                                                                                  Obj7, Obj8, "", "", "", "", "", "")
                            End If

                        End If

                    End If
                    ICurrentRowIndex += 1
                Next


                PubGoodsDataSet.Tables(0).Rows.Clear()

                Dim rowTemp As DataGridViewRow

                '刪除空白行
                For i As Integer = Me.dgrd3.Rows.Count - 1 To 0 Step -1
                    If IsDBNull(Me.dgrd3.Rows(i).Cells("Code").Value) Then
                        Me.dgrd3.Rows.RemoveAt(i)

                    End If

                    '判斷是否為新建行
                    If Me.dgrd3.Rows(i).IsNewRow = True And Me.dgrd3.Rows(i).Cells("code").Value <> "" Then
                        rowTemp = Me.dgrd3.Rows(i)
                        Obj1 = Me.dgrd3.Rows(i).Cells("Barcode").Value
                        Obj2 = Me.dgrd3.Rows(i).Cells("Code").Value
                        Obj3 = Me.dgrd3.Rows(i).Cells("Cnname").Value
                        Obj4 = Me.dgrd3.Rows(i).Cells("Enname").Value
                        Obj5 = Me.dgrd3.Rows(i).Cells("Color").Value
                        Obj6 = Me.dgrd3.Rows(i).Cells("Spec").Value
                        Obj7 = Me.dgrd3.Rows(i).Cells("Unit").Value
                        Obj8 = Me.dgrd3.Rows(i).Cells("Price").Value
                        For K As Integer = 0 To Me.dgrd3.Columns.Count - 1

                            Me.dgrd3.Rows(i).Cells(K).Value = ""
                        Next
                        Me.dgrd3.Rows.Insert(IorgRowIndex, "", "", Obj1, Obj2, Obj3, Obj4, Obj5, Obj6, _
                                                                                Obj7, Obj8, "", "", "", "", "", "")
                    End If
                Next



                Me.dgrd3.Refresh()

                UpdateSN()
            End If
        End If
    End Sub

#End Region


    Private Sub mnuDelStyle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDelStyle.Click
        DeldgvStyle(Me)
    End Sub

    Private Sub Panel7_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel7.Paint

    End Sub

    Private Sub GroupBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub
End Class

